From 884b075291929f00ce3906da1050ce40f1b9ac95 Mon Sep 17 00:00:00 2001 From: ibnu Date: Thu, 23 Nov 2023 15:26:39 +0700 Subject: [PATCH 001/155] update conflict --- app/Http/Controllers/ProjectController.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 42bcb6d..80296af 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -344,6 +344,12 @@ class ProjectController extends Controller return response()->json(['status'=>'success','code'=>200, 'data' => $data], 200); } +// testing + public function calculateSCurvetest(Request $request){ + $data = MasterFunctionsHelper::calculateSCurve($request->project_id); + return response()->json(['status'=>'success','code'=>200, 'data' => $data], 200); +} + public function calculateSCurve(Request $request){ $sCurve = Project::select('scurve')->where('id', $request->project_id)->first(); return response()->json(['status'=>'success','code'=>200, 'data' => json_decode($sCurve->scurve)], 200); From 3ea5783ea6c530a155c9f7512609ffe04afe9a55 Mon Sep 17 00:00:00 2001 From: ibnu Date: Thu, 23 Nov 2023 15:29:22 +0700 Subject: [PATCH 002/155] update curva calculation --- app/Helpers/MasterFunctionsHelper.php | 419 +++++++++++++++++++++++--- rest-client.http | 109 +++++-- routes/web.php | 1 + 3 files changed, 458 insertions(+), 71 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index 78f3326..bf2ee73 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -162,7 +162,7 @@ class MasterFunctionsHelper return $dataFinal; } - public function calculateProgressBasedOnReportMaterial($keyGantt) + public function calculateProgressBasedOnReportMaterialOld($keyGantt) { DB::enableQueryLog(); @@ -488,6 +488,325 @@ class MasterFunctionsHelper return $dataFinal; } + public function calculateProgressBasedOnReportMaterial($keyGantt) + { + DB::enableQueryLog(); + + $dataFinal = []; + $dataPayload = []; + $dataPayload['period'] = 'week'; + $totalACWP = 0; + $totalBCWP = 0; + $tempPercentage = []; + + $dataProject = Project::find($keyGantt['proyek_id']); + $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->first(); + if (isset($dataPayload['end_date']) && $dataPayload['end_date'] > $dataProject->akhir_proyek) { + $dataPayload['end_date'] = $dataProject->akhir_proyek; + } + + if ($dataHeader) { + $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); + } else { + $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); + } + + if (!Activity::where("version_gantt_id", $keyGantt['id'])->first()) + return $dataFinal; + + // $alreadyHasReport = DB::table('report_activity_material as a') + // ->select('a.id') + // ->join('m_activity as b', 'b.id', '=', 'a.activity_id') + // ->where('b.version_gantt_id', '=', $keyGantt['id']) + // ->exists(); + // note : delete this + // if(!$alreadyHasReport) + // return $dataFinal; + + $minDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('start_date')->first(); + + $begin = new \DateTime($minDate); + $begin->modify('last Monday'); + if (isset($dataPayload['end_date'])) { + $maxDate = $dataPayload['end_date']; + $end = new \DateTime($maxDate . ' Friday'); + $end->modify('next Friday'); + $end->modify('next Friday'); + /* $interval = \DateInterval::createFromDateString('1 day'); */// should be using this but its bugged + $interval = new \DateInterval('P7D'); + } else { + $actualMaxDate = DB::table('assign_material_to_activity as ama') + ->where("ama.proyek_id", $keyGantt['proyek_id']) + ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') + ->where('a.version_gantt_id', '=', $keyGantt['id']) + ->max("a.end_date"); // plan date overlapped with assign_material_to_activity's, it should be m_activity's + $plannedMaxDate = DB::table('assign_material_to_activity as ama') + ->where("ama.proyek_id", $keyGantt['proyek_id']) + ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') + ->where('a.version_gantt_id', '=', $keyGantt['id']) + ->max("a.planned_end"); // plan date overlapped with assign_material_to_activity's, it should be m_activity' + $maxDate = max(new \DateTime($plannedMaxDate), new \DateTime($actualMaxDate)); + $end = new \DateTime($maxDate->format('Y-m-d') . ' Friday'); + $end->modify('next Friday'); + $end->modify('next Friday'); + $interval = new \DateInterval('P7D'); + } + $period = new \DatePeriod($begin, $interval, $end); + + $arr_ActualM = []; + $tempDate = []; + $tempPercentagePlan = []; + $tempPercentagePlanWhr = []; + $tempPercentageReal = []; + $tempTtlPercentPlan = 0; + $tempTtlPercentActual = 0; + + $currentACWP = 0; + $currentBCWP = 0; + + foreach ($period as $dt) { + $minSevenDays = new \Datetime($dt->format("Y-m-d")); + $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); + $tempDate[] = array($dt->format("Y-m-d")); + // $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('a.version_gantt_id', '=', $keyGantt['id']) + // ->whereDate('ama.plan_date', '<=',$dt->format("Y-m-d")) + // ->whereDate('ama.plan_date', '>', $minSevenDays) + // ->get(); + + $activities = DB::table('m_activity AS a') + ->join('assign_material_to_activity AS amta', 'amta.activity_id', '=', 'a.id') + ->where('a.type_activity', 'task') + ->where('a.bobot_planning', '>', 0) + ->where('a.version_gantt_id', $keyGantt['id']) + ->whereDate('amta.plan_date', '<=', $dt->format("Y-m-d")) + ->whereDate('amta.plan_date', '>', $minSevenDays) + ->select('a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress', 'a.id'); + + $dataPlanM = DB::table('m_activity AS a') + ->join('assign_hr_to_activity AS ahta', 'ahta.activity_id', '=', 'a.id') + ->where('a.type_activity', 'task') + ->where('a.bobot_planning', '>', 0) + ->where('a.version_gantt_id', $keyGantt['id']) + ->whereDate('a.start_date', '<=', $dt->format("Y-m-d")) + ->whereDate('a.start_date', '>', $minSevenDays) + ->select('a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress', 'a.id') + ->union($activities) + ->get(); + + $dataActualM = DB::table('report_activity_material as ram') + ->select('ram.activity_id', 'ram.qty', 'ram.report_date', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') + ->join('m_activity as a', 'a.id', '=', 'ram.activity_id') + ->where('a.version_gantt_id', '=', $keyGantt['id']) + ->where('a.proyek_id', '=', $keyGantt['proyek_id']) + ->whereDate('ram.report_date', '<=', $dt->format("Y-m-d")) + ->whereDate('ram.report_date', '>', $minSevenDays) + ->get(); + $dataTempPlan = []; + $x = 0; + $sumPercentagePlan = 0; + $totalACWP = isset($totalACWP) ? $totalACWP : 0; + $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; + + foreach ($dataPlanM as $keyPlanM) { + // $sumVolPlan = DB::table(function ($query) use ($keyGantt) { + // $query->select('a.*') + // ->from('m_activity AS a') + // ->join('assign_material_to_activity as amta', 'amta.activity_id', '=', 'a.id') + // ->where('a.type_activity', 'task') + // ->where('a.bobot_planning', '>', 0) + // ->where('a.version_gantt_id', $keyGantt['id']) + // ->unionAll(function ($query) use ($keyGantt) { + // $query->select('a.*') + // ->from('m_activity AS a') + // ->join('assign_hr_to_activity as ahta', 'ahta.activity_id', '=', 'a.id') + // ->where('a.type_activity', 'task') + // ->where('a.bobot_planning', '>', 0) + // ->where('a.version_gantt_id', $keyGantt['id']); + // }) + // ->orderBy('id', 'asc'); + // }, 'subquery') + // ->sum('bobot_planning'); + $sumVolPlan = DB::table('assign_material_to_activity') + ->select('activity_id', DB::raw('SUM(qty_planning) as ttl_qty_plan')) + ->where('activity_id', '=', $keyPlanM->id) + ->groupBy('activity_id') + ->first(); + if($keyPlanM->duration){ + $weekCount = $keyPlanM->duration / 7; + $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; + // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + // $bobotHari = $keyPlanM->bobot_planning / $keyPlanM->duration; + }else{ + $weeklyProgress = 0; + + } + + // $weeklyPlan = $weekCount > 0 ? $keyPlanM->bobot_planning / $weekCount : 0; + // $weeklyProgress = $weeklyPlan * $keyPlanM->bobot_planning; + $dataTempPlan[$x]['activity_id'] = $keyPlanM->id; + $dataTempPlan[$x]['bobot_planning'] = $keyPlanM->bobot_planning; + $dataTempPlan[$x]['ttl_plan'] = $sumVolPlan; + $dataTempPlan[$x]['biaya_actual'] = $keyPlanM->biaya_actual; + $dataTempPlan[$x]['duration'] = $keyPlanM->duration; + $dataTempPlan[$x]['persentase_progress'] = $keyPlanM->persentase_progress; + try { + $dataTempPlan[$x]['percentage'] = $keyPlanM->bobot_planning; + $sumPercentagePlan += $weeklyProgress; + if (isset($keyPlanM->duration) && $keyPlanM->duration > 0) + $totalBCWP += (((($keyPlanM->persentase_progress * $keyPlanM->bobot_planning) / 100) / $keyPlanM->duration) * $totalRencanaBudget) / 100; + else + $totalBCWP = 0; + $dataTempPlan[$x]['totalBCWP'] = $totalBCWP; + } catch (\DivisionByZeroError $e) { + return response()->json(['message' => $e->getMessage()]); + } + $x++; + } + + $w = 0; + $dataTempReport = []; + $sumPercentageActual = 0; + foreach ($dataActualM as $keyActualM) { + $sumVolActual = DB::table('assign_material_to_activity') + ->select('activity_id', DB::raw('SUM(qty_planning) as ttl_qty_plan')) + ->where('activity_id', '=', $keyActualM->activity_id) + ->groupBy('activity_id') + ->first(); + $sumReportActual = DB::table('report_activity_material') + ->where('activity_id', $keyActualM->activity_id) + ->sum('qty'); + $reportCount = DB::table('report_activity_material')->where('activity_id', '=', $keyActualM->activity_id)->count(); + $dataTempReport[$w]['activity_id'] = $keyActualM->activity_id; + $dataTempReport[$w]['qty'] = $keyActualM->qty; + $dataTempReport[$w]['report_date'] = $keyActualM->report_date; + $dataTempReport[$w]['bobot_planning'] = $keyActualM->bobot_planning; + $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; + try { + // assign_material_to_activity + $checkStatusActivity = DB::table('assign_material_to_activity') + ->select('activity_id', 'status_activity') + ->where('activity_id', '=', $keyActualM->activity_id) + ->orderBy('status_activity', 'ASC') + ->first(); + $dataTempReport[$w]['percentage'] = ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; + // $sumPercentageActual+=($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; + // if($keyActualM->qty/$sumVolActual->ttl_qty_plan >= 1){ + if ($checkStatusActivity->status_activity == 'done') { + $sumPercentageActual += $keyActualM->bobot_planning / $reportCount; + // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; + } else { + if ($keyActualM->qty / $sumVolActual->ttl_qty_plan >= 1 || (int) $sumVolActual->ttl_qty_plan == (int) $sumReportActual) { + $sumPercentageActual += (($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning) * (95 / 100); + // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; + } else { + $sumPercentageActual += ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; + // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; + } + } + // }else { + // if($checkStatusActivity->status_activity == 'done'){ + // $sumPercentageActual+=($keyActualM->qty/$keyActualM->qty)*$keyActualM->bobot_planning; + // }else{ + // $sumPercentageActual+=($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; + // } + // } + + + $totalACWP += $keyActualM->duration > 0 ? $keyActualM->biaya_actual / $keyActualM->duration : 0; + } catch (\DivisionByZeroError $e) { + return response()->json(['message' => $e->getMessage()]); + } + $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') { + $tempTtlPercentPlan += $sumPercentagePlan; + $tempTtlPercentActual += $sumPercentageActual; + + $currentACWP += $totalACWP; + $currentBCWP += $totalBCWP; + + $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); + $tempPercentagePlan[] = round($tempTtlPercentPlan, 2); + $tempPercentagePlanWhr[] = ["weekly period", $tempPercentagePlan]; + $tempPercentageReal[] = round($tempTtlPercentActual, 2); + if ($tempTtlPercentPlan >= 100 && $tempTtlPercentActual >= 100) { + break; + } + } else { + $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); + $tempPercentagePlan[] = round($sumPercentagePlan, 2); + $tempPercentageReal[] = round($sumPercentageActual, 2); + } + } + + try { + if (round($totalACWP, 0) > $totalRencanaBudget) { + $estimatedCost = round($totalACWP, 0) + 0; + } else { + $estimatedCost = ($totalRencanaBudget + 0); + } + } catch (\DivisionByZeroError $e) { + return response()->json([ + 'message' => $e->getMessage(), + "line" => 566, + 'gantt' => $keyGantt, + ]); + } + $estimatedCost = $totalACWP > $totalRencanaBudget ? $totalACWP : $totalRencanaBudget; + + $costDeviation = $totalRencanaBudget - $estimatedCost; + if ($costDeviation > 0) { + $potential = "SAVING"; + } else { + $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; + } + + $lastReal = $tempPercentageReal[count($tempPercentageReal) - 1]; + $totalBCWP = $lastReal * $dataProject->rencana_biaya / 100; + $dataResponse = array( + "date" => $tempDate, + "percentage" => $tempPercentage, + "percentagePlan" => $tempPercentagePlan, + "percentageReal" => $tempPercentageReal, + "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" => $potential, + ) + ); + + $dataFinal[] = array( + "proyek_name" => $dataProject->nama, + "data" => $dataResponse, + "gantt" => $keyGantt + ); + + return $dataFinal; + } + public function calculateSCurveVWahyu($projectId) { DB::enableQueryLog(); @@ -807,8 +1126,8 @@ class MasterFunctionsHelper $dataFinal = []; $dataPayload = []; $dataPayload['period'] = 'week'; - $totalACWP = 0; - $totalBCWP = 0; + // $totalACWP = 0; + // $totalBCWP = 0; $tempPercentage = []; $dataProject = Project::find($projectId); @@ -830,13 +1149,13 @@ class MasterFunctionsHelper $minDate = $dataProject->mulai_proyek; - $begin = new \DateTime($minDate . ' Monday'); + $begin = new \DateTime($minDate); $begin->modify('last Monday'); if (isset($dataPayload['end_date'])) { $maxDate = $dataPayload['end_date']; $end = new \DateTime($maxDate . ' Friday'); $end->modify('next Friday'); - $end->modify('next Friday'); + // $end->modify('next Friday'); /* $interval = \DateInterval::createFromDateString('1 day'); */// should be using this but its bugged $interval = new \DateInterval('P7D'); } else { @@ -860,8 +1179,8 @@ class MasterFunctionsHelper $tempTtlPercentPlan = 0; $tempTtlPercentActual = 0; - $currentACWP = 0; - $currentBCWP = 0; + // $currentACWP = 0; + // $currentBCWP = 0; foreach ($period as $dt) { $minSevenDays = new \Datetime($dt->format("Y-m-d")); @@ -905,8 +1224,8 @@ class MasterFunctionsHelper $dataTempPlan = []; $x = 0; $sumPercentagePlan = 0; - $totalACWP = isset($totalACWP) ? $totalACWP : 0; - $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; + // $totalACWP = isset($totalACWP) ? $totalACWP : 0; + // $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; foreach ($dataPlanM as $keyPlanM) { // $sumVolPlan = DB::table(function ($query) use ($projectId) { @@ -932,9 +1251,14 @@ class MasterFunctionsHelper ->groupBy('activity_id') ->first(); - $weekCount = 1; // jadiin perhari (1) - $weeklyPlan = $sumVolPlan->ttl_qty_plan / $weekCount; - $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + if($keyPlanM->duration){ + $weekCount = $keyPlanM->duration / 7; + // $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; + $weeklyPlan = $weekCount > 0 ? $sumVolPlan->ttl_qty_plan / $weekCount : 0; + $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + }else{ + $weeklyProgress = 0; + } // $weeklyPlan = $sumVolPlan->ttl_qty_plan / $weekCount; // $weeklyProgress = 80; @@ -947,11 +1271,11 @@ class MasterFunctionsHelper try { $dataTempPlan[$x]['percentage'] = $keyPlanM->bobot_planning; $sumPercentagePlan += $weeklyProgress; - if (isset($keyPlanM->duration) && $keyPlanM->duration > 0) - $totalBCWP += (((($keyPlanM->persentase_progress * $keyPlanM->bobot_planning) / 100) / $keyPlanM->duration) * $totalRencanaBudget) / 100; - else - $totalBCWP = 0; - $dataTempPlan[$x]['totalBCWP'] = $totalBCWP; + // if (isset($keyPlanM->duration) && $keyPlanM->duration > 0) + // $totalBCWP += (((($keyPlanM->persentase_progress * $keyPlanM->bobot_planning) / 100) / $keyPlanM->duration) * $totalRencanaBudget) / 100; + // else + // $totalBCWP = 0; + // $dataTempPlan[$x]['totalBCWP'] = $totalBCWP; } catch (\DivisionByZeroError $e) { return response()->json(['message' => $e->getMessage()]); } @@ -1027,11 +1351,11 @@ class MasterFunctionsHelper // } - $totalACWP += $keyActualM->duration > 0 ? $keyActualM->biaya_actual / $keyActualM->duration : 0; + // $totalACWP += $keyActualM->duration > 0 ? $keyActualM->biaya_actual / $keyActualM->duration : 0; } catch (\DivisionByZeroError $e) { return response()->json(['message' => $e->getMessage()]); } - $dataTempReport[$w]['totalacwp'] = $totalACWP; + // $dataTempReport[$w]['totalacwp'] = $totalACWP; $w++; } @@ -1049,8 +1373,8 @@ class MasterFunctionsHelper // if ($tempTtlPercentPlan >= 100) // $tempTtlPercentPlan = 100; - $currentACWP += $totalACWP; - $currentBCWP += $totalBCWP; + // $currentACWP += $totalACWP; + // $currentBCWP += $totalBCWP; $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); $tempPercentagePlan[] = round($tempTtlPercentPlan, 2); @@ -1067,37 +1391,40 @@ class MasterFunctionsHelper $tempDate[] = array($dt->format("Y-m-d")); } - try { - if (round($totalACWP, 0) > $totalRencanaBudget) { - $estimatedCost = round($totalACWP, 0) + 0; - } else { - $estimatedCost = ($totalRencanaBudget + 0); - } - } catch (\DivisionByZeroError $e) { - return response()->json([ - 'message' => $e->getMessage(), - "line" => 566, - ]); - } - $estimatedCost = $totalACWP > $totalRencanaBudget ? $totalACWP : $totalRencanaBudget; - - $costDeviation = $totalRencanaBudget - $estimatedCost; - if ($costDeviation > 0) { - $potential = "SAVING"; - } else { - $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; - } - - $lastReal = $tempPercentageReal[count($tempPercentageReal) - 1]; - $totalBCWP = $lastReal * $dataProject->rencana_biaya / 100; + // try { + // if (round($totalACWP, 0) > $totalRencanaBudget) { + // $estimatedCost = round($totalACWP, 0) + 0; + // } else { + // $estimatedCost = ($totalRencanaBudget + 0); + // } + // } catch (\DivisionByZeroError $e) { + // return response()->json([ + // 'message' => $e->getMessage(), + // "line" => 566, + // ]); + // } + // $estimatedCost = $totalACWP > $totalRencanaBudget ? $totalACWP : $totalRencanaBudget; + + // $costDeviation = $totalRencanaBudget - $estimatedCost; + // if ($costDeviation > 0) { + // $potential = "SAVING"; + // } else { + // $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; + // } + + // $lastReal = $tempPercentageReal[count($tempPercentageReal) - 1]; + // $lastReal = $tempPercentageReal[count($tempPercentageReal) < 1 ? count($tempPercentageReal) : count($tempPercentageReal) - 1]; + // $totalBCWP = $lastReal * $dataProject->rencana_biaya / 100; $dataResponse = array( "date" => $tempDate, - "start" => $begin, + "start" => $minDate, + "begin" => $begin, + // "periode" => $period, "end" => $end, "percentage" => $tempPercentage, "percentagePlan" => $tempPercentagePlan, "percentageReal" => $tempPercentageReal, - "data_details" => $arr_ActualM, + // "data_details" => $arr_ActualM, // "budget_control" => array( // "current_budget" => $totalRencanaBudget, // "acwp" => round($totalACWP, 0), diff --git a/rest-client.http b/rest-client.http index 772aee0..6abe9ab 100644 --- a/rest-client.http +++ b/rest-client.http @@ -1,4 +1,5 @@ -@token = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODQ0NFwvYXBpXC9sb2dpbiIsImlhdCI6MTY5MTc2MDYyNCwiZXhwIjoxNjkyMzY1NDI0LCJuYmYiOjE2OTE3NjA2MjQsImp0aSI6Ikd2bEFPTE4yZ2FuRFdVbjEiLCJzdWIiOjEsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.XNGbsmcgQ-CkV8vLlvnItGKM0R1am5X5b6qUFOR1DRo +@token = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9iYWNrZW5kLnRlc3RcL2FwaVwvbG9naW4iLCJpYXQiOjE3MDA0NTA1ODYsImV4cCI6MTcwMTA1NTM4NiwibmJmIjoxNzAwNDUwNTg2LCJqdGkiOiJack9MMU04UGdKWGkwTUU1Iiwic3ViIjoxLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.fyg6CyiCAcX3GD4iSy8urkHpZEJ4mnXSXQc4NKC8U9A + @tokenS = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9hZHctYXBpLm9zcHJvLmlkXC9hcGlcL2xvZ2luIiwiaWF0IjoxNjkxNTcyMTIwLCJleHAiOjE2OTIxNzY5MjAsIm5iZiI6MTY5MTU3MjEyMCwianRpIjoiVUdqbnhLRVdlZzYyTTBnayIsInN1YiI6MSwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.5QqK0dLW5jzbVOkSCSW0mFo0K7ycGOBW9NCG_2Zldm4 @@ -6,7 +7,7 @@ # @hostname = https://ospro-api.ospro.id/api # @hostname = https://api-iu.ospro.id/api # @hostname = https://api-staging-adw.ospro.id/api -@hostname = http://localhost:8444/api +@hostname = http://backend.test/api # @hostname = http://103.73.125.81:8444/api # @hostname = http://localhost:8444/adw-backend/api @@ -418,7 +419,7 @@ content-type: application/json "operator": "AND" } ], - "select": ["kode_sortname", "nama", "mulai_proyek"], + "select": ["id", "nama", "rencana_biaya", "type_proyek_id", "currency_symbol", "mulai_proyek", "akhir_proyek"], "joins": [ { "name": "m_users", @@ -455,7 +456,43 @@ Authorization: Bearer {{tokenS}} content-type: application/json { - "columns":[{"name":"nama","logic_operator":"ilike","value":"","operator":"AND"}],"joins":[{"name":"m_users","column_join":"pm_id","column_results":["name","username"]},{"name":"m_type_proyek","column_join":"type_proyek_id","column_results":["name","description"]}],"orders":{"columns":["id"],"ascending":false},"paging":{"start":0,"length":10} + "columns": [ + { + "name": "nama", + "logic_operator": "ilike", + "value": "", + "operator": "AND" + } + ], + "select": ["id", "nama", "rencana_biaya", "color_progress", "currency_symbol", "mulai_proyek", "akhir_proyek"], + "joins": [ + { + "name": "m_users", + "column_join": "pm_id", + "column_results": [ + "name", + "username" + ] + }, + { + "name": "m_type_proyek", + "column_join": "type_proyek_id", + "column_results": [ + "name", + "description" + ] + } + ], + "orders": { + "columns": [ + "id" + ], + "ascending": false + }, + "paging": { + "start": 0, + "length": 10 + } } ### add @@ -529,7 +566,7 @@ content-type: application/json ###### Activity ### get data by id version -GET {{hostname}}/activity/33/29/get +GET {{hostname}}/activity/550/137/get Authorization: Bearer {{token}} content-type: application/json @@ -785,24 +822,37 @@ content-type: application/json ### -POST {{hostname}}/activity/get-curva-s +POST {{hostname}}/dashboard/curva-s Authorization: Bearer {{token}} content-type: application/json { - "project_id": [47], - "period": "week" + "project_id": [15] } +### +POST {{hostname}}/project/s-curve-command-test +Authorization: Bearer {{token}} +content-type: application/json + + {"period":"week","project_id":"129","gantt_id":"862"} +### {"period":"week","project_id":"129","gantt_id":"862"} ### -POST {{hostname}}/dashboard/curva-s +POST {{hostname}}/project/calculate-s-curve Authorization: Bearer {{token}} content-type: application/json -{ - "project_id": [15] -} +{"period":"week","project_id":"129","gantt_id":"862"} +### {"period":"week","project_id":"135","gantt_id":"891"} + +####### +POST {{hostname}}/project/get-s-curve +Authorization: Bearer {{token}} +content-type: application/json + +{"period":"week","project_id":"129","gantt_id":"800"} +### {"period":"week","project_id":"135","gantt_id":"891"} ### GET https://adw-api.ospro.id/api/request-material/get-material-integration?name=c @@ -957,6 +1007,27 @@ content-type: application/json "user_id": 1247 } + +# -6.226761,106.809311 jkarta +# -6.465806,106.760559 +# -6.356175,108.336182 indramayu +# -6.266805,106.468048, tigaraksa +# -6.205115,106.918373 jatinegara +###### +POST {{hostname}}/presence/test +Authorization: Bearer {{token}} +content-type: application/json + +{ + "clock_in_out": { + "clock_out_lat": -6.356175, + "clock_out_lng": 108.336182, + "type" : "out" + }, + "time": "2023-08-15T14:48:17+07:00", + "user_id": 1566 +} + ###### POST {{hostname}}/presence/add Authorization: Bearer {{token}} @@ -1016,9 +1087,7 @@ POST {{hostname}}/map-monitoring/search Authorization: Bearer {{token}} content-type: application/json -{ - "project_id" : [75, 76, 78] -} +{"project_id":[140,138,132,130]} ###### POST {{hostname}}/waypoint/add-bulk @@ -1159,13 +1228,3 @@ content-type: application/json } } -####### -POST {{hostname}}/project/get-s-curve -Authorization: Bearer {{token}} -content-type: application/json - -{ - "period":"week", - "project_id":"118", - "gantt_id":"287" -} \ No newline at end of file diff --git a/routes/web.php b/routes/web.php index f9e79b4..5d9bcfa 100644 --- a/routes/web.php +++ b/routes/web.php @@ -69,6 +69,7 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->post('/project/get-s-curve', 'ProjectController@getSCurve'); $router->post('/project/calculate-s-curve', 'ProjectController@calculateSCurve'); $router->post('/project/s-curve-command', 'ProjectController@sCurveCommand'); + $router->post('/project/s-curve-command-test', 'ProjectController@calculateSCurvetest'); $router->post('/project/get-linear-s-curve', 'ProjectController@getLinearSCurve'); $router->post('/project/get-overdue-activities', 'ProjectController@getOverdueActivities'); $router->post('/project/get-integration-invoice', 'ProjectController@getInvoiceIntegration'); From e68e270772d5625aacb784e7ccc757218eaecbe4 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Sat, 25 Nov 2023 00:59:47 +0700 Subject: [PATCH 003/155] company crud --- app/Http/Controllers/CompanyController.php | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 7e8938d..3a0cecb 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -3,6 +3,7 @@ namespace App\Http\Controllers; use App\Models\Company; +use App\Models\MenuCompany; use Illuminate\Http\Request; class CompanyController extends Controller @@ -10,18 +11,22 @@ class CompanyController extends Controller public function add(Request $request) { $this->validate($request, [ - 'name' => 'required', - 'description' => 'required' + 'company_name' => 'required', + 'registration_no' => 'required', + 'template_id' => 'required', + 'is_active' => 'required' ]); $data = $request->all(); $data['created_by'] = $this->currentName; - + if(isset($data['base_url']) && $data['base_url'] != NULL) { + $data['base_url'] = json_encode($data['base_url'], true); + } $result = Company::create($data); if ($result) { - return response()->json(['status' => 'success', 'message' => 'add Company successfully!', 'code' => 200], 200); + return response()->json(['status' => 'success','data' => $result, 'message' => 'add Company successfully!', 'code' => 200], 200); } else { return response()->json(['status' => 'failed', 'message' => 'add data Company failed!', 'code' => 400], 400); } @@ -51,6 +56,10 @@ class CompanyController extends Controller $data = Company::find($id); + if(isset($data['base_url']) && $data['base_url'] != NULL) { + $data->update(['base_url'=>null]); + $data['base_url'] = json_encode($data['base_url'], true); + } if ($data) { $result = $data->update($request->all()); } else { @@ -71,6 +80,7 @@ class CompanyController extends Controller $data = Company::find($id); if ($data) { + MenuCompany::where('company_id',$id)->delete(); $delete = $data->delete(); } else { return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); From 0efc17deeeef6c42602ae3b62424d0cae1ebf65a Mon Sep 17 00:00:00 2001 From: wahyuun Date: Sat, 25 Nov 2023 01:00:37 +0700 Subject: [PATCH 004/155] update multiple method --- .../Controllers/MenuCompanyController.php | 45 +++++++------------ 1 file changed, 16 insertions(+), 29 deletions(-) diff --git a/app/Http/Controllers/MenuCompanyController.php b/app/Http/Controllers/MenuCompanyController.php index 2b79748..d59c734 100644 --- a/app/Http/Controllers/MenuCompanyController.php +++ b/app/Http/Controllers/MenuCompanyController.php @@ -9,33 +9,15 @@ use Illuminate\Support\Facades\Log; class MenuCompanyController extends Controller { - // public function add(Request $request) - // { - // $this->validate($request, [ - // 'icon' => 'required', - // 'name' => 'string|required', - // 'url' => 'required|unique:m_company_menu,url', - // 'sequence' => 'required|integer', - // ]); - - // $data = $request->all(); - - // $data['created_by'] = $this->currentName; - - // $result = MenuCompany::create($data); - - // if ($result) { - // return response()->json(['status' => 'success', 'message' => 'add data menu successfully!', 'code' => 200], 200); - // } else { - // return response()->json(['status' => 'failed', 'message' => 'add data menu failed!', 'code' => 400], 400); - // } - // } - public function addMultiple(Request $request) { $menus = $request->all(); - if (is_array($menus) && count($menus) > 0) { + $data = MenuCompany::where('company_id',$menus[0]['company_id']); + if($data){ + $data->delete(); + } + if (is_array($menus) && count($menus) > 0 && isset($menus[0]['menu_id'])) { $countRes = 0; foreach ($menus as $menu) { @@ -60,12 +42,17 @@ class MenuCompanyController extends Controller } if ($countRes > 0) { - return response()->json(['status' => 'success', 'message' => 'add data menu successfully!', 'code' => 200]); + return response()->json(['status' => 'success', 'message' => 'Add data menu successfully!', 'code' => 200]); } else { - return response()->json(['status' => 'failed', 'message' => 'add data menu failed created!', 'code' => 400]); + return response()->json(['status' => 'failed', 'message' => 'Add data menu failed created!', 'code' => 500]); } } else { - return response()->json(['status' => 'failed', 'message' => 'add data menu failed created!', 'code' => 400]); + if(isset($data)) + { + return response()->json(['status' => 'success', 'message' => 'Add data menu successfully!', 'code' => 200]); + }else{ + return response()->json(['status' => 'failed', 'message' => 'Add data menu failed created!', 'code' => 500]); + } } } @@ -120,15 +107,15 @@ class MenuCompanyController extends Controller if ($data) { $delete = $data->delete(); } else { - return response()->json(['status' => 'failed', 'message' => 'data menu not found!', 'code' => 400], 400); + return response()->json(['status' => 'failed', 'message' => 'Data menu not found!', 'code' => 400], 400); die(); } if ($delete) { - return response()->json(['status' => 'success', 'message' => 'data menu successfully deleted!', 'code' => 200], 200); + return response()->json(['status' => 'success', 'message' => 'Data menu successfully deleted!', 'code' => 200], 200); } else { - return response()->json(['status' => 'failed', 'message' => 'data menu failed deleted!', 'code' => 400], 400); + return response()->json(['status' => 'failed', 'message' => 'Data menu failed deleted!', 'code' => 400], 400); } } From 7372d1801edb5a1dc125a089e6262842c913f42a Mon Sep 17 00:00:00 2001 From: wahyuun Date: Sat, 25 Nov 2023 01:01:08 +0700 Subject: [PATCH 005/155] update model --- app/Models/Company.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/Models/Company.php b/app/Models/Company.php index db52f7d..2dc38e5 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -31,7 +31,6 @@ class Company extends Model 'created_at', 'created_by', 'updated_at', - 'updated_by', - 'company_id' + 'updated_by' ]; } From e6dc6b11c88fecafa294295a7465694718b130ea Mon Sep 17 00:00:00 2001 From: farhantock Date: Mon, 27 Nov 2023 12:52:26 +0700 Subject: [PATCH 006/155] filter project --- app/Http/Controllers/ProjectController.php | 581 +++++++++++---------- 1 file changed, 308 insertions(+), 273 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index ca92810..3015327 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -50,7 +50,7 @@ class ProjectController extends Controller { $this->validate($request, [ 'nama' => 'required', - 'mulai_proyek' => 'required', + 'mulai_proyek' => 'required', 'akhir_proyek' => 'required', 'rencana_biaya' => 'required', 'type_proyek_id' => 'required' @@ -59,81 +59,82 @@ class ProjectController extends Controller $data = $request->all(); $data['created_by'] = $this->currentName; + $data['created_by_id'] = $this->currentId; - if(empty($data['phase_id'])) + if (empty($data['phase_id'])) $data['phase_id'] = 1; $result = Project::create($data); - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500], 500); + 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); + 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); + 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::query() - ->from('m_proyek AS mp') - ->where('mp.id', $id) - ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); + $result = Project::query() + ->from('m_proyek AS mp') + ->where('mp.id', $id) + ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); - if (!is_null($result->first()['divisi_id'])) { - $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') - ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); - } + if (!is_null($result->first()['divisi_id'])) { + $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') + ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); + } - $result = $result->first(); + $result = $result->first(); - if(!$result) - return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - return response()->json(['status'=>'success','code'=> 200,'data'=>$result], 200); + 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); + 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); + 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); + 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); + 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 + "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); @@ -145,15 +146,15 @@ class ProjectController extends Controller { $data = Project::find($id); - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + 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); + 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); + return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); } private function deleteRelative($project_id) @@ -168,12 +169,12 @@ class ProjectController extends Controller ProjectChecklists::where('proyek_id', $project_id)->delete(); ProjectIssues::where('proyek_id', $project_id)->delete(); ProjectRisks::where('proyek_id', $project_id)->delete(); - ProjectToChecklistK3::where('proyek_id', $project_id)->delete(); - HierarchyFtth::where('project_id', $project_id)->delete(); - AssignTools::where('proyek_id', $project_id)->delete(); - OfficeHours::where('proyek_id', $project_id)->delete(); - ReportK3::where('proyek_id', $project_id)->delete(); - RequestMaterial::where('proyek_id', $project_id)->delete(); + ProjectToChecklistK3::where('proyek_id', $project_id)->delete(); + HierarchyFtth::where('project_id', $project_id)->delete(); + AssignTools::where('proyek_id', $project_id)->delete(); + OfficeHours::where('proyek_id', $project_id)->delete(); + ReportK3::where('proyek_id', $project_id)->delete(); + RequestMaterial::where('proyek_id', $project_id)->delete(); $this->deleteVersionGantt($project_id); $this->deleteDokumenProject($project_id); } @@ -188,16 +189,16 @@ class ProjectController extends Controller 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); + 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); + if (file_exists($this->pathActivityDocument . $ad->file)) { + unlink($this->pathActivityDocument . $ad->file); } } ActivityDokumen::whereIn("activity_id", $activityIds)->delete(); @@ -215,8 +216,8 @@ class ProjectController extends Controller $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); + 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(); @@ -225,8 +226,8 @@ class ProjectController extends Controller $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); + if (file_exists($this->pathDocument . $dokumen->file)) { + unlink($this->pathDocument . $dokumen->file); } } @@ -240,11 +241,11 @@ class ProjectController extends Controller $dataBuilder = $this->setUpPayload($payload, 'm_proyek'); $builder = $dataBuilder['builder']; $countBuilder = $dataBuilder['count']; - // $builder->where("selfTable.created_by",$this->currentName); + // $builder->where("selfTable.created_by",$this->currentName); $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } public function list() @@ -286,101 +287,109 @@ class ProjectController extends Controller 'created_by', 'updated_at', 'updated_by' - )->orderBy('id', 'desc') - // ->where("created_by",$this->currentName) - ->get(); + )->orderBy('id', 'desc') + // ->where("created_by",$this->currentName) + ->get(); $countData = $data->count(); - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + if (!$data) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - $totalPlannedCost = array_sum(array_map('intval', array_column($data->toArray(), 'plannedCost'))); - $totalActualCost = $data->sum('actualCost'); + $totalPlannedCost = array_sum(array_map('intval', array_column($data->toArray(), 'plannedCost'))); + $totalActualCost = $data->sum('actualCost'); $manpowers = User::count(); $projectsOnDanger = Project::where('budget_health', 'overrun')->count(); - $projectPhases = ProjectPhase::orderBy('order', 'asc')->pluck('name'); - $projectTypes = ProjectType::orderBy('id', 'asc')->pluck('name'); - try { - $projectsByPhase = DB::table('m_proyek') - ->select('m_proyek_phase.name', 'm_proyek_phase.color', DB::raw('count(*) as total')) - ->join('m_proyek_phase', 'm_proyek_phase.id', '=', 'm_proyek.phase_id') - ->groupBy('m_proyek_phase.name', 'm_proyek_phase.color') - ->get(); - } catch (\Exception $e) { - return response()->json(['message' => $e->getMessage()]); - } - try { - $projectsByType = DB::table('m_proyek') - ->select('m_type_proyek.name', DB::raw('count(m_type_proyek.id) as total')) - ->join('m_type_proyek', 'm_type_proyek.id', '=', 'm_proyek.type_proyek_id') - ->groupBy('m_type_proyek.name') - ->get(); - } catch (\Exception $e) { - return response()->json(['message' => $e->getMessage()]); - } + $projectPhases = ProjectPhase::orderBy('order', 'asc')->pluck('name'); + $projectTypes = ProjectType::orderBy('id', 'asc')->pluck('name'); + try { + $projectsByPhase = DB::table('m_proyek') + ->select('m_proyek_phase.name', 'm_proyek_phase.color', DB::raw('count(*) as total')) + ->join('m_proyek_phase', 'm_proyek_phase.id', '=', 'm_proyek.phase_id') + ->groupBy('m_proyek_phase.name', 'm_proyek_phase.color') + ->get(); + } catch (\Exception $e) { + return response()->json(['message' => $e->getMessage()]); + } + try { + $projectsByType = DB::table('m_proyek') + ->select('m_type_proyek.name', DB::raw('count(m_type_proyek.id) as total')) + ->join('m_type_proyek', 'm_type_proyek.id', '=', 'm_proyek.type_proyek_id') + ->groupBy('m_type_proyek.name') + ->get(); + } catch (\Exception $e) { + return response()->json(['message' => $e->getMessage()]); + } return response()->json( - [ - 'status'=>'success', - 'code'=>200, - 'data'=>$data, - 'totalRecord'=>$countData, - 'totalPlannedCost' => $totalPlannedCost, - 'totalActualCost' => $totalActualCost, - 'totalRevenue' => $totalPlannedCost - $totalActualCost, - 'manpowers' => $manpowers, - 'projectsOnDanger'=> $projectsOnDanger, - 'projectPhases' => $projectPhases, - 'projectsByPhase' => $projectsByPhase, - 'projectTypes' => $projectTypes, - 'projectsByType' => $projectsByType, - ], 200); + [ + 'status' => 'success', + 'code' => 200, + 'data' => $data, + 'totalRecord' => $countData, + 'totalPlannedCost' => $totalPlannedCost, + 'totalActualCost' => $totalActualCost, + 'totalRevenue' => $totalPlannedCost - $totalActualCost, + 'manpowers' => $manpowers, + 'projectsOnDanger' => $projectsOnDanger, + 'projectPhases' => $projectPhases, + 'projectsByPhase' => $projectsByPhase, + 'projectTypes' => $projectTypes, + 'projectsByType' => $projectsByType, + ], + 200 + ); } - public function getListProjectTask($id){ - $data = UserToActivity::select("assign_hr_to_activity.user_id as user_id","m_proyek.*") + 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); + if (!$data) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - return response()->json(['status'=>'success','code'=>200,'data'=>$data], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } - public function getSCurve(Request $request){ + public function getSCurve(Request $request) + { $data = MasterFunctionsHelper::getSCurve($request); - return response()->json(['status'=>'success','code'=>200, 'data' => $data], 200); - } + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } - public function calculateSCurve(Request $request){ - $sCurve = Project::select('scurve')->where('id', $request->project_id)->first(); - return response()->json(['status'=>'success','code'=>200, 'data' => json_decode($sCurve->scurve)], 200); - } + public function calculateSCurve(Request $request) + { + $sCurve = Project::select('scurve')->where('id', $request->project_id)->first(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => json_decode($sCurve->scurve)], 200); + } - public function sCurveCommand(Request $request){ - Artisan::call('calculate:scurve', [ - 'project_id' => $request->project_id - ]); - // $project = Project::find($request->project_id); + public function sCurveCommand(Request $request) + { + Artisan::call('calculate:scurve', [ + 'project_id' => $request->project_id + ]); + // $project = Project::find($request->project_id); - // if ($project) { - // dispatch(new ProcessSCurve($project)); + // if ($project) { + // dispatch(new ProcessSCurve($project)); - // return response()->json(['message' => 'S Curve calculation queued']); - // } + // return response()->json(['message' => 'S Curve calculation queued']); + // } - // return response()->json(['message' => 'Project not found'], 404); - } + // return response()->json(['message' => 'Project not found'], 404); + } - public function getLinearSCurve(Request $request){ + public function getLinearSCurve(Request $request) + { $data = MasterFunctionsHelper::getLinearSCurve($request); - return response()->json(['status'=>'success','code'=>200, 'data' => $data], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } - public static function setSyncDate($activity_id, $activity, $report) { + public static function setSyncDate($activity_id, $activity, $report) + { $status = AssignMaterial::where('activity_id', $activity_id)->first(); if (!isset($status)) { $reports = array( @@ -412,17 +421,17 @@ class ProjectController extends Controller return $reports; } - public function synchronizeReport($gantt_id) + public function synchronizeReport($gantt_id) { $activities = Activity::where("version_gantt_id", $gantt_id)->get(); $reports = []; - foreach($activities as $activity) { + foreach ($activities as $activity) { $activity_id = $activity->id; $countReports = ReportActivityMaterial::where('activity_id', $activity_id)->count(); if ($countReports === 1) { $dataReports = ReportActivityMaterial::where('activity_id', $activity_id)->orderBy('report_date')->get(); - foreach($dataReports as $dr) { + foreach ($dataReports as $dr) { $reports[] = ProjectController::setSyncDate($activity_id, $activity, $dr); } } @@ -443,15 +452,15 @@ class ProjectController extends Controller /* return response()->json(['status'=>'success','data'=> $reports,'code'=>200], 200); */ /* return response()->json(['status'=>'success','data'=> $activities,'code'=>200], 200); */ - for ($i=0; $i < count($reports); $i++) { + for ($i = 0; $i < count($reports); $i++) { $activity = Activity::find($reports[$i]['activity_id']); - if($reports[$i]['status'] != 'done'){ + if ($reports[$i]['status'] != 'done') { $reports[$i]['max_date']->modify('-1 day'); - }else if($reports[$i]['status'] == 'done'){ - $activity->actual_end = $reports[$i]['max_date']->setTime(23,59,59); + } else if ($reports[$i]['status'] == 'done') { + $activity->actual_end = $reports[$i]['max_date']->setTime(23, 59, 59); } $activity->start_date = $reports[$i]['min_date']; //same early - $activity->end_date = $reports[$i]['max_date']->setTime(23,59,59); // same early + $activity->end_date = $reports[$i]['max_date']->setTime(23, 59, 59); // same early $startDate = new DateTime($activity->start_date); $endDate = new DateTime($activity->end_date); $duration = MasterFunctionsHelper::countDays($activity->version_gantt_id, $startDate, $endDate); @@ -460,7 +469,7 @@ class ProjectController extends Controller $activity->save(); } - return response()->json(['status'=>'success','message'=>'Synchronize to report success!','code'=>200], 200); + return response()->json(['status' => 'success', 'message' => 'Synchronize to report success!', 'code' => 200], 200); } public function setBaseline($gantt_id) @@ -469,127 +478,127 @@ class ProjectController extends Controller foreach ($activities as $activity) { $activity->update([ - "planned_start"=>$activity->start_date, - "planned_end"=>$activity->end_date, - "early_start"=>$activity->start_date, - "early_end"=>$activity->end_date, + "planned_start" => $activity->start_date, + "planned_end" => $activity->end_date, + "early_start" => $activity->start_date, + "early_end" => $activity->end_date, ]); } - return response()->json(['status'=>'success','message'=>'Set baseline success!','code'=> 200], 200); + return response()->json(['status' => 'success', 'message' => 'Set baseline success!', 'code' => 200], 200); } - public function getInvoiceIntegration(Request $request) { - $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); + public function getInvoiceIntegration(Request $request) + { + $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); $search = urlencode($request->search); - if(empty($search)) - return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw').'/project_cost?project_no=SEARCH'); + if (empty($search)) + return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); + $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); $response = MasterFunctionsHelper::curlReq($url); - if (isset($request->gantt_id)) { - $response->data->total_cost = $response->data->total_cost / $ganttCount; - } + if (isset($request->gantt_id)) { + $response->data->total_cost = $response->data->total_cost / $ganttCount; + } + + return response()->json(['status' => 'success', 'data' => $response, 'code' => 200], 200); + } + public function getByUser($id) + { + $alias = "utp"; + $userProyek = UserToProyek::query() + ->from('assign_hr_to_proyek AS ' . $alias) + ->where([ + ['is_customer', true], + ['user_id', $id] + ]) + ->leftJoin('m_users', $alias . '.user_id', '=', 'm_users.id') + ->leftJoin('m_proyek', $alias . '.proyek_id', '=', 'm_proyek.id') + ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') + ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name', 'm_users.name AS join_first_name') + ->get(); + $totalRecord = $userProyek->count(); - return response()->json(['status'=>'success', 'data'=> $response, 'code'=>200], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); } - public function getByUser($id) - { - $alias = "utp"; - $userProyek = UserToProyek::query() - ->from('assign_hr_to_proyek AS ' . $alias) - ->where([ - ['is_customer', true], - ['user_id', $id] - ]) - ->leftJoin('m_users', $alias.'.user_id', '=', 'm_users.id') - ->leftJoin('m_proyek', $alias.'.proyek_id', '=', 'm_proyek.id') - ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') - ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name','m_users.name AS join_first_name') - ->get(); - $totalRecord = $userProyek->count(); - - return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); - } - public function detail(Request $request, $id, $gantt_id = null, $s_curve = null){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + public function detail(Request $request, $id, $gantt_id = null, $s_curve = null) + { + 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); - if (!isset($gantt_id)) { - $gantt = MasterFunctionsHelper::getLatestGantt($id); - $ganttId = $gantt['last_gantt_id']; - } else { - $ganttId = $gantt_id; - } + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + if (!isset($gantt_id)) { + $gantt = MasterFunctionsHelper::getLatestGantt($id); + $ganttId = $gantt['last_gantt_id']; + } else { + $ganttId = $gantt_id; + } $result->projectManager = User::where('id', $result->pm_id)->value('name'); - if (isset($s_curve)) { - $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->first(); - $actualStartExist = Activity::where('proyek_id', $id)->whereNotNull('actual_start')->exists(); - if($result['type_proyek_id'] === 9) - { - $actualEndExist = Activity::where('proyek_id', $id)->exists(); - $query = Activity::where('proyek_id', $id); - }else{ - $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); - $query = Activity::where('version_gantt_id', $ganttId); - } - } else { - $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $ganttId)->first(); - $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); - $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); - $query = Activity::where('version_gantt_id', $ganttId); - } - - if ($actualStartExist) { - $startDate = $query->orderBy('actual_start')->value('start_date'); - } else { - $startDate = $query->orderBy('start_date')->value('start_date'); - } - if($actualEndExist) - { - $maxEndDate = $query->max('id'); - $endDate = $query->where('id',$maxEndDate)->first()->end_date; - } - - $plannedStart = Activity::where('version_gantt_id', $ganttId) - ->orderBy('planned_start') - ->value('planned_start'); - $plannedEnd = Activity::where('version_gantt_id', $ganttId) - ->orderByDesc('planned_end') - ->value('planned_end'); - $result->header->start_date = $startDate; - $result->header->end_date = $endDate; - $result->header->planned_start = $plannedStart; - $result->header->planned_end = $plannedEnd; - return response()->json(['status'=>'success','code'=> 200,'data'=>$result, 'gantt'=>$ganttId], 200); + if (isset($s_curve)) { + $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->first(); + $actualStartExist = Activity::where('proyek_id', $id)->whereNotNull('actual_start')->exists(); + if ($result['type_proyek_id'] === 9) { + $actualEndExist = Activity::where('proyek_id', $id)->exists(); + $query = Activity::where('proyek_id', $id); + } else { + $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $query = Activity::where('version_gantt_id', $ganttId); + } + } else { + $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $ganttId)->first(); + $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); + $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $query = Activity::where('version_gantt_id', $ganttId); + } + + if ($actualStartExist) { + $startDate = $query->orderBy('actual_start')->value('start_date'); + } else { + $startDate = $query->orderBy('start_date')->value('start_date'); + } + if ($actualEndExist) { + $maxEndDate = $query->max('id'); + $endDate = $query->where('id', $maxEndDate)->first()->end_date; + } + + $plannedStart = Activity::where('version_gantt_id', $ganttId) + ->orderBy('planned_start') + ->value('planned_start'); + $plannedEnd = Activity::where('version_gantt_id', $ganttId) + ->orderByDesc('planned_end') + ->value('planned_end'); + $result->header->start_date = $startDate; + $result->header->end_date = $endDate; + $result->header->planned_start = $plannedStart; + $result->header->planned_end = $plannedEnd; + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result, 'gantt' => $ganttId], 200); } - public function getOverdueActivities(Request $request){ + public function getOverdueActivities(Request $request) + { $payload = $request->all(); - if(empty($payload['id']) || !is_int((int)$payload['id'])) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + if (empty($payload['id']) || !is_int((int)$payload['id'])) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); $result = Project::find($payload['id']); - if(!$result) - return response()->json(['status'=>'failed','message'=> 'Project not found!','code'=> 404], 404); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Project not found!', 'code' => 404], 404); //TODO possible overdue bug $endDate = Activity::where('proyek_id', $payload['id']) ->orderByDesc('end_date') ->value('end_date'); - if(isset($payload['till_date'])) { + if (isset($payload['till_date'])) { if (isset($payload['scurve'])) { - $overdueActivities = Activity::where('proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::where('proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); } else { - $overdueActivities = Activity::where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); } - } - else { + } else { if (isset($payload['scurve'])) { $overdueActivities = Activity::where('proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); } else { @@ -598,53 +607,75 @@ class ProjectController extends Controller } $result->overdueActivities = $overdueActivities; - return response()->json(['status'=>'success','code'=> 200,'data'=>$result], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); } - public function getReportDistribution(Request $request){ + public function getReportDistribution(Request $request) + { $payload = $request->all(); - if(empty($payload['project_id']) || !is_int((int)$payload['project_id'])) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + if (empty($payload['project_id']) || !is_int((int)$payload['project_id'])) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); $reports = DB::table('assign_material_to_activity as ama') - ->select('u.name', 'a.name as activity_name', 'ama.qty_planning', 'ram.qty as qty_real','rm.description as material_name', 'rm.uom as material_unit', - 'ram.lat', 'ram.lon', 'ram.description as report_notes', 'ram.report_date') + ->select( + 'u.name', + 'a.name as activity_name', + 'ama.qty_planning', + 'ram.qty as qty_real', + 'rm.description as material_name', + 'rm.uom as material_unit', + 'ram.lat', + 'ram.lon', + 'ram.description as report_notes', + 'ram.report_date' + ) ->join('report_activity_material as ram', 'ram.assign_material_id', '=', 'ama.id') ->join('m_req_material as rm', 'rm.id', '=', 'ama.material_id') ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') ->join('m_users as u', 'u.id', '=', 'ram.user_id') ->where('ama.proyek_id', '=', $payload['project_id']) ->whereNotNull('ram.lat') - ->whereBetween('ram.report_date', [$payload['start_date'], $payload['end_date']]); + ->whereBetween('ram.report_date', [$payload['start_date'], $payload['end_date']]); - return response()->json(['status'=>'success', 'code'=> 200, 'data'=> $reports], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $reports], 200); } - public function getManpower($proyek_id){ + public function getManpower($proyek_id) + { $manCount = UserToProyek::where('proyek_id', $proyek_id)->count(); - return response()->json(['totalRecord'=>$manCount]); + return response()->json(['totalRecord' => $manCount]); } - public function getAssignedHR($gantt_id){ + public function getAssignedHR($gantt_id) + { $results = UserToActivity::select('assign_hr_to_activity.proyek_id', 'assign_hr_to_activity.user_id', 'm_activity.id', 'm_activity.name', 'm_activity.start_date', 'm_activity.end_date') ->join('m_activity', 'm_activity.id', '=', 'assign_hr_to_activity.activity_id') ->where('assign_hr_to_activity.version_gantt_id', $gantt_id) ->get(); - return response()->json(['data'=>$results]); + return response()->json(['data' => $results]); } public function dashboard($id) { $data = DB::table('m_proyek as mp') - ->select('mp.kode_sortname', 'mp.nama as name_project', 'mp.mulai_proyek as start', 'mp.akhir_proyek as finish', - 'mp.rencana_biaya', 'mp.company', 'mp.currency_symbol', 'mu.name as pm', 'mp.budget_health') - ->join('m_users as mu', 'mu.id', '=', 'mp.pm_id') - ->where('mp.id', $id) - ->first(); - - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data tidak ditemukan!','code'=> 404], 404); + ->select( + 'mp.kode_sortname', + 'mp.nama as name_project', + 'mp.mulai_proyek as start', + 'mp.akhir_proyek as finish', + 'mp.rencana_biaya', + 'mp.company', + 'mp.currency_symbol', + 'mu.name as pm', + 'mp.budget_health' + ) + ->join('m_users as mu', 'mu.id', '=', 'mp.pm_id') + ->where('mp.id', $id) + ->first(); + + if (!$data) + return response()->json(['status' => 'failed', 'message' => 'Data tidak ditemukan!', 'code' => 404], 404); $manpowers = UserToProyek::where('proyek_id', $id)->count(); $rootActivity = Activity::whereNull('parent_id')->where('proyek_id', $id)->orderBy('version_gantt_id', 'desc')->first(); @@ -653,38 +684,42 @@ class ProjectController extends Controller $progress = @$rootActivity->persentase_progress ?? 0; $commentActivity = DB::table('m_comment_activity as mca') - ->select('mca.activity_id', 'mca.comment as comment', 'mca.created_by as comment_by', 'mca.created_at as comment_created', - 'ma.name as activity') - ->join('m_activity as ma', 'ma.id', '=', 'mca.activity_id') - ->where('ma.proyek_id', $id) - ->orderBy('comment_by') - ->take(2) - ->get(); + ->select( + 'mca.activity_id', + 'mca.comment as comment', + 'mca.created_by as comment_by', + 'mca.created_at as comment_created', + 'ma.name as activity' + ) + ->join('m_activity as ma', 'ma.id', '=', 'mca.activity_id') + ->where('ma.proyek_id', $id) + ->orderBy('comment_by') + ->take(2) + ->get(); $data->actual_cost = $actualCost; $data->progress = $progress; $data->comment = $commentActivity; $data->man_power = $manpowers; - return response()->json(['status'=>'success','code'=>200,'data'=> $data], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } - private function httpReq($search){ - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, str_replace("ADDR", $search, API_GEOLOCATION)); + private function httpReq($search) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, str_replace("ADDR", $search, API_GEOLOCATION)); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); $info = curl_getinfo($ch); - $output = curl_exec($ch); - curl_close($ch); + $output = curl_exec($ch); + curl_close($ch); - return json_decode($output); + return json_decode($output); } - } - From fa54ad6227ac49fa5993bc4ae8993451573d2c8d Mon Sep 17 00:00:00 2001 From: ibnu Date: Mon, 27 Nov 2023 16:04:21 +0700 Subject: [PATCH 007/155] update scurve --- app/Helpers/MasterFunctionsHelper.php | 23 +++- app/Http/Controllers/ActivityController.php | 125 ++++++++++++++++++++ routes/web.php | 3 + 3 files changed, 145 insertions(+), 6 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index bf2ee73..9baaa80 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -642,7 +642,11 @@ class MasterFunctionsHelper $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; // $bobotHari = $keyPlanM->bobot_planning / $keyPlanM->duration; }else{ - $weeklyProgress = 0; + // $weeklyProgress = 0; + $weekCount = 1 / 7; + $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; + // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; } @@ -776,10 +780,11 @@ class MasterFunctionsHelper $potential = "SAVING"; } else { $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; - } - + } $lastReal = $tempPercentageReal[count($tempPercentageReal) - 1]; $totalBCWP = $lastReal * $dataProject->rencana_biaya / 100; + array_pop($tempPercentageReal); + array_pop($tempPercentageReal); $dataResponse = array( "date" => $tempDate, "percentage" => $tempPercentage, @@ -1253,11 +1258,17 @@ class MasterFunctionsHelper if($keyPlanM->duration){ $weekCount = $keyPlanM->duration / 7; - // $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; - $weeklyPlan = $weekCount > 0 ? $sumVolPlan->ttl_qty_plan / $weekCount : 0; + $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; + // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + // $bobotHari = $keyPlanM->bobot_planning / $keyPlanM->duration; }else{ - $weeklyProgress = 0; + // $weeklyProgress = 0; + $weekCount = 1 / 7; + $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; + // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + } // $weeklyPlan = $sumVolPlan->ttl_qty_plan / $weekCount; diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index 21dc80c..eabfcc6 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -37,6 +37,94 @@ class ActivityController extends Controller return response()->json(['status' => 'success', 'data' => $dataGantt, 'code' => 200], 200); } + public function activitySCurve($proyek_id, $gantt_id){ + + // "data": [ + // { + // "id": 1, + // "text": "Office itinerancy", + // "type": "project", + // "order": "10", + // "progress": 0.4, + // "open": true, + // "user":"0", + // "start_date": "02-04-2024 00:00", + // "duration": 17, + // "end_date": "19-04-2024 00:00", + // "parent": 0 + // } + // ], + // "links": [ + // { + // "id": "1", + // "source": "1", + // "target": "2", + // "type": "1" + // } + // ] + // } + + $checkHeader = Activity::where('version_gantt_id', $gantt_id)->where('type_activity', 'header')->count(); + $finalData = []; + if ($checkHeader > 0) { + $dataHeader = Activity::select('id', 'name as text', 'type_activity as type', 'persentase_progress as progress', 'start_date', 'end_date', 'duration', 'parent_id', 'sortorder as order')->where('version_gantt_id', $gantt_id)->where('type_activity', 'header')->first(); + + // $dataHeader->start_date1 = isset($dataHeader->start) ? date_format(date_create($dataHeader->start), "d-m-Y H:i") : NULL; + // $dataHeader->end_date1 = isset($dataHeader->end) ? date_format(date_create($dataHeader->end), "d-m-Y H:i") : NULL; + + $dataHeader->progress = $dataHeader->progress / 100; + + $dataHeader->type = "project"; + $dataHeader->text = $dataHeader->name; + $finalData[] = $dataHeader; + $data = Activity::select('id', 'name as text', 'type_activity as type', 'persentase_progress as progress', 'start_date', 'end_date', 'duration', 'parent_id', 'sortorder as order')->where('version_gantt_id', $gantt_id)->where('parent_id', $dataHeader->id)->orderBy('sortorder', 'asc')->get(); + } else { + $data = Activity::select('id', 'name as text', 'type_activity as type', 'persentase_progress as progress', 'start_date', 'end_date', 'duration', 'parent_id', 'sortorder as order')->where('version_gantt_id', $gantt_id)->whereNull('parent_id')->orderBy('sortorder', 'asc')->get(); + } + + foreach ($data as $objRow) { + $type = "project"; + $dataChildren = $this->getChildrenSCurve($gantt_id, $objRow->id); + + if ($objRow->type_activity == "milestone") + $type = $objRow->type_activity; + if (empty($dataChildren)) + $type = "task"; + + $objRow->parent = $objRow->parent_id ? $objRow->parent_id : null; + // $objRow->start_date = isset($objRow->start) ? date_format(date_create($objRow->start), "d-m-Y H:i") : NULL; + // $objRow->end_date1 = isset($objRow->end) ? date_format(date_create($objRow->end), "d-m-Y H:i") : NULL; + + $objRow->progress = $objRow->persentase_progress / 100; + $objRow->type = $type; + $finalData[] = $objRow; + $finalData = array_merge($finalData, $dataChildren); + } + + $dataLink = Link::where('version_gantt_id', $gantt_id)->get(); + $finalLink = []; + foreach ($dataLink as $objRow) { + $dataRow = array( + 'id' => $objRow->id, + 'source' => $objRow->s_activity_id, + 'target' => $objRow->t_activity_id, + 'type' => $objRow->type_link, + 'code' => $objRow->code_link + ); + if ($objRow->lag) + $dataRow['lag'] = $objRow->lag; + $finalLink[] = $dataRow; + } + + $resultData = array( + "data" => $finalData, + "links" => $finalLink + ); + + return response()->json(['status' => 'success', 'data' => $resultData, 'code' => 200], 200); + + } + private function getDataActivity($id) { $checkHeader = Activity::where('version_gantt_id', $id)->where('type_activity', 'header')->count(); @@ -116,6 +204,43 @@ class ActivityController extends Controller return $resultData; } + private function getChildrenSCurve($gantt_id, $parent_id) + { + $finalData = []; + + $data = Activity::select('id', 'name as text', 'type_activity as type', 'bobot_planning', 'persentase_progress as progress', 'start_date', 'end_date', 'duration', 'parent_id', 'sortorder as order') + ->where('version_gantt_id', $gantt_id)->where('parent_id', $parent_id)->orderBy('sortorder', 'asc')->get(); + foreach ($data as $objRow) { + $objRow->parent = $parent_id; + $objRow->progress = (float) $objRow->bobot_planning /100; + // $objRow->start_date1 = isset($objRow->start) ? date_format(date_create($objRow->start), "d-m-Y H:i") : NULL; + // $objRow->end_date1 = isset($objRow->end) ? date_format(date_create($objRow->end), "d-m-Y H:i") : NULL; + + $dataChildren = $this->getChildrenSCurve($gantt_id, $objRow->id); + if ($objRow->type_activity == "milestone") { + $objRow->type = $objRow->type_activity; + // $objRow->actual_start = isset($objRow->actual_start) ? date_format(date_create($objRow->actual_start), "d-m-Y") : NULL; + } elseif (empty($dataChildren)) { + $objRow->type = "task"; + // $objRow->actual_start = isset($objRow->actual_start) ? date_format(date_create($objRow->actual_start), "d-m-Y") : NULL; + // $objRow->actual_end = isset($objRow->actual_end) ? date_format(date_create($objRow->actual_end), "d-m-Y") : NULL; + // if(isset($objRow->actual_start)){ + // $objRow->auto_scheduling = false; + // } + } else { + $objRow->type = "project"; + // $actualStart = $this->getFirstLastDateActivity($objRow->id, "start"); + // $objRow->actual_start = isset($actualStart) ? date_format(date_create($actualStart), "d-m-Y") : NULL; + + // $actualEnd = $this->getFirstLastDateActivity($objRow->id, "end"); + // $objRow->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "d-m-Y") : NULL; + } + $finalData[] = $objRow; + $finalData = array_merge($finalData, $dataChildren); + } + return $finalData; + } + private function getChildren($gantt_id, $parent_id) { $finalData = []; diff --git a/routes/web.php b/routes/web.php index 5d9bcfa..14e1d08 100644 --- a/routes/web.php +++ b/routes/web.php @@ -75,6 +75,7 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->post('/project/get-integration-invoice', 'ProjectController@getInvoiceIntegration'); $router->post('/project/get-report-distribution', 'ProjectController@getReportDistribution'); + /* $router->get('/project/get-expenditure/{id}/{date?}', 'ProjectController@getExpenditure'); */ /* $router->get('/project/get-total-expenditure/{id}', 'ProjectController@getTotalExpenditure'); */ /* $router->get('/project/get-status-health-schedule/{id}', 'ProjectController@getStatusSchedule'); */ @@ -214,6 +215,8 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->post('/activity/import-old', 'ActivityController@importOld'); $router->post('/activity/batch-update/{ganttId}', 'ActivityController@batchUpdate'); $router->get('/activity/update-schedule/{ganttId}', 'ActivityController@updateSchedule'); + $router->get('/activity/s-curve/{proyek_id}/{gantt_id}', 'ActivityController@activitySCurve'); + $router->post('/task', 'ActivityController@add'); $router->get('/task/edit/{id}', 'ActivityController@edit'); $router->put('/task/{id}', 'ActivityController@update'); From 1cfc01dad20be6cfdf8b0a989efdd5e9db4d6bff Mon Sep 17 00:00:00 2001 From: wahyu Date: Mon, 27 Nov 2023 19:14:24 +0700 Subject: [PATCH 008/155] limit actual progress till today --- app/Helpers/MasterFunctionsHelper.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index 9baaa80..c45954e 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -739,6 +739,8 @@ class MasterFunctionsHelper 'plan' => $dataTempPlan, 'actual' => $dataTempReport, ); + $today = new DateTime(); + $date = new DateTime($dt->format("Y-m-d")); if (isset($dataPayload['period']) && $dataPayload['period'] == 'week') { $tempTtlPercentPlan += $sumPercentagePlan; $tempTtlPercentActual += $sumPercentageActual; @@ -749,14 +751,18 @@ class MasterFunctionsHelper $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); $tempPercentagePlan[] = round($tempTtlPercentPlan, 2); $tempPercentagePlanWhr[] = ["weekly period", $tempPercentagePlan]; + if ($date < $today) { $tempPercentageReal[] = round($tempTtlPercentActual, 2); + } if ($tempTtlPercentPlan >= 100 && $tempTtlPercentActual >= 100) { break; } } else { $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); $tempPercentagePlan[] = round($sumPercentagePlan, 2); + if ($date < $today) { $tempPercentageReal[] = round($sumPercentageActual, 2); + } } } @@ -783,8 +789,6 @@ class MasterFunctionsHelper } $lastReal = $tempPercentageReal[count($tempPercentageReal) - 1]; $totalBCWP = $lastReal * $dataProject->rencana_biaya / 100; - array_pop($tempPercentageReal); - array_pop($tempPercentageReal); $dataResponse = array( "date" => $tempDate, "percentage" => $tempPercentage, From ba5447c3ff4c0529d7a7d48399f1db48716a181c Mon Sep 17 00:00:00 2001 From: ibnu Date: Mon, 27 Nov 2023 20:49:18 +0700 Subject: [PATCH 009/155] update fix curva --- app/Helpers/MasterFunctionsHelper.php | 28 +++++++++------------------ 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index c45954e..f1e9058 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -514,15 +514,6 @@ class MasterFunctionsHelper if (!Activity::where("version_gantt_id", $keyGantt['id'])->first()) return $dataFinal; - // $alreadyHasReport = DB::table('report_activity_material as a') - // ->select('a.id') - // ->join('m_activity as b', 'b.id', '=', 'a.activity_id') - // ->where('b.version_gantt_id', '=', $keyGantt['id']) - // ->exists(); - // note : delete this - // if(!$alreadyHasReport) - // return $dataFinal; - $minDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('start_date')->first(); $begin = new \DateTime($minDate); @@ -568,14 +559,6 @@ class MasterFunctionsHelper $minSevenDays = new \Datetime($dt->format("Y-m-d")); $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); $tempDate[] = array($dt->format("Y-m-d")); - // $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('a.version_gantt_id', '=', $keyGantt['id']) - // ->whereDate('ama.plan_date', '<=',$dt->format("Y-m-d")) - // ->whereDate('ama.plan_date', '>', $minSevenDays) - // ->get(); $activities = DB::table('m_activity AS a') ->join('assign_material_to_activity AS amta', 'amta.activity_id', '=', 'a.id') @@ -1381,6 +1364,9 @@ class MasterFunctionsHelper 'plan' => $dataTempPlan, 'actual' => $dataTempReport, ); + + $today = new DateTime(); + $date = new DateTime($dt->format("Y-m-d")); if (isset($dataPayload['period']) && $dataPayload['period'] == 'week') { $tempTtlPercentPlan += $sumPercentagePlan; $tempTtlPercentActual += $sumPercentageActual; @@ -1394,14 +1380,18 @@ class MasterFunctionsHelper $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); $tempPercentagePlan[] = round($tempTtlPercentPlan, 2); $tempPercentagePlanWhr[] = ["weekly period", $tempPercentagePlan]; - $tempPercentageReal[] = round($tempTtlPercentActual, 2); + if ($date < $today) { + $tempPercentageReal[] = round($tempTtlPercentActual, 2); + } // if ($tempTtlPercentPlan >= 100 && $tempTtlPercentActual >= 100) { // break; // } } else { $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); $tempPercentagePlan[] = round($sumPercentagePlan, 2); - $tempPercentageReal[] = round($sumPercentageActual, 2); + if ($date < $today) { + $tempPercentageReal[] = round($sumPercentageActual, 2); + } } $tempDate[] = array($dt->format("Y-m-d")); } From ad59e5f3ec52fdf2e0726bafad03eb157609a846 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 29 Nov 2023 00:18:37 +0700 Subject: [PATCH 010/155] update response --- app/Http/Controllers/UserToProyekController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/UserToProyekController.php b/app/Http/Controllers/UserToProyekController.php index f6fca59..0e8736e 100644 --- a/app/Http/Controllers/UserToProyekController.php +++ b/app/Http/Controllers/UserToProyekController.php @@ -64,10 +64,10 @@ class UserToProyekController extends Controller if($countRes > 0){ return response()->json(['status'=>'success' ,'message'=>'Project customer successfull created','code'=>200]); }else{ - return response()->json(['status'=>'success' ,'message'=>'Project customer failed created','code'=>400]); + return response()->json(['status'=>'failed' ,'message'=>'Project customer failed created','code'=>400]); } }else{ - return response()->json(['status'=>'success' ,'message'=>'Project customer successfull created','code'=>200]); + return response()->json(['status'=>'failed' ,'message'=>'Project customer failed created','code'=>200]); } } From 0266e75ada77fe6240b36bdb9d28357a9cff7184 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 29 Nov 2023 00:19:02 +0700 Subject: [PATCH 011/155] create API db-carousel --- .../ProjectCarausellController.php | 455 ++++++------------ 1 file changed, 136 insertions(+), 319 deletions(-) diff --git a/app/Http/Controllers/ProjectCarausellController.php b/app/Http/Controllers/ProjectCarausellController.php index 7c2eb06..361b8b1 100644 --- a/app/Http/Controllers/ProjectCarausellController.php +++ b/app/Http/Controllers/ProjectCarausellController.php @@ -5,351 +5,168 @@ namespace App\Http\Controllers; use App\Models\{ User, Project, - Activity, - HierarchyFtth, - ProjectComment, VersionGantt, - UserToProyek, - UserToActivity, - Presence + ProjectIssues, + ProjectRisks }; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\DB; -use App\Helpers\MasterFunctionsHelper; -use Carbon\Carbon; - class ProjectCarausellController extends Controller { - // public function invoke($id) - // { - // $dateStart = Carbon::now()->startOfDay(); - // $dateEnd = Carbon::now()->endOfDay(); - // // Mengatur waktu awal bulan dan mengurangkan 1 tahun - // $startDate = Carbon::now()->startOfMonth()->subYear()->format('Y-m-d'); - // // Mengatur waktu saat ini dan mengurangkan 1 tahun - // $endDate = Carbon::now()->subYear()->format('Y-m-d'); - - // if(empty($id) || !is_int((int)$id)){ - // return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - // } - - // $result = Project::select('id','nama','budget_health','kode_sortname','pm_id','rencana_biaya','company','scurve','calculation_status')->find($id); - // if(!$result){ - // return response()->json(['status'=>'failed','message'=> 'Project not found!','code'=> 404], 404); - // } - // $ganttData = VersionGantt::where('proyek_id', $id) - // ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete') - // ->get(); - - // // Get Id Gantt & hierarchy_ftth_id - // $gantt_id = $ganttData->pluck('id')->toArray(); - // $hierarchy_ftth_id = $ganttData->pluck('hierarchy_ftth_id')->toArray(); - - // // Heararchy - // $finalData = []; - // if($hierarchy_ftth_id){ - // $ftth = HierarchyFtth::whereIn('id',$hierarchy_ftth_id)->get(); - // if($ftth->first() != null) - // { - // array_push($finalData, $ftth->first()); - // } - // if($ftth->where('parent_id','!=', null)->first()){ - // $this->getParents($finalData, $ftth->pluck('parent_id')->toArray()); - // } - // } else { - // return $finalData; - // } - - // // SCurve - // $SCurve = MasterFunctionsHelper::getSCurveCarausell($result['id'],$gantt_id,'week'); - - // // Overdue Activities - // $endDate = Activity::where('proyek_id', $result['id']) - // ->orderByDesc('end_date') - // ->value('end_date'); - // $overdueActivities = Activity::whereIn('version_gantt_id', $gantt_id)->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); - - // // Project Comment - // $projectComment = ProjectComment::query() - // ->select('project_id','gantt_id','comment','created_at') - // ->where('project_id',$result['id']) - // ->whereIn('gantt_id',$gantt_id) + // public function invoke() { + // // Master Data + // $projectData = Project::query() + // ->select("id","nama","kode_sortname","pm_id","budget_health","calculation_status","mulai_proyek","akhir_proyek","rencana_biaya","company","scurve") // ->get(); - - // // Manpower - // $manCount = UserToProyek::where('proyek_id', $result['id'])->count(); - // // Assigned - // $utAct = UserToActivity::query() - // ->whereIn('version_gantt_id', $gantt_id) - // ->get(); - // // Actual - // $presence = Presence::whereBetween('clock_in', [$dateStart, $dateEnd]) - // ->select('m_users.name','m_users.ktp_number') - // ->join('m_users','t_clock_in_out.user_id','m_users.id') - // ->get(); - - // // Report distribution - // $reportsDistribution = DB::table('assign_material_to_activity as ama') - // ->select('u.name', 'a.name as activity_name', 'ama.qty_planning', 'ram.qty as qty_real','rm.description as material_name', 'rm.uom as material_unit', - // 'ram.lat', 'ram.lon', 'ram.description as report_notes', 'ram.report_date') - // ->join('report_activity_material as ram', 'ram.assign_material_id', '=', 'ama.id') - // ->join('m_req_material as rm', 'rm.id', '=', 'ama.material_id') - // ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') - // ->join('m_users as u', 'u.id', '=', 'ram.user_id') - // ->where('ama.proyek_id', '=', $result['id']) - // ->whereNotNull('ram.lat') - // ->whereBetween('ram.report_date', [$startDate, $startDate]); - - // // Check Existing - // $actualStartExist = Activity::whereIn('version_gantt_id',$gantt_id)->whereNotNull('actual_start')->exists(); - // $actualEndExist = Activity::whereIn('version_gantt_id',$gantt_id)->exists(); - - // $query = Activity::query()->whereIn('version_gantt_id', $gantt_id); - // // Start - // if ($actualStartExist) { - // $startDate = $query->select('version_gantt_id',DB::raw('MIN(start_date) as min_start')) - // ->groupBy('version_gantt_id') - // ->get(); - // } else { - // $startDate = $query->select('version_gantt_id',DB::raw('MIN(start_date) as min_start','version_gantt_id')) - // ->groupBy('version_gantt_id') - // ->orderBy('min_start', 'ASC') - // ->get(); - // } - // // End - // if($actualEndExist) - // { - // $maxIds = $query->selectRaw('MAX(id) as max_id') - // ->groupBy('version_gantt_id') - // ->pluck('max_id', 'version_gantt_id'); - - // $endDate = Activity::whereIn('id', $maxIds)->select('end_date','version_gantt_id')->get(); - // } - - // $plannedStart = $query->selectRaw('MIN(planned_start) as min_planned_start, version_gantt_id') - // ->groupBy('version_gantt_id') - // ->orderBy('min_planned_start') + // $projectRisk = ProjectRisks::query() + // ->select('proyek_id','description','level_risk','preventive_risk') // ->get(); - // $plannedEnd = $query->selectRaw('MAX(planned_end) as max_planned_end, version_gantt_id') - // ->groupBy('version_gantt_id') - // ->orderByDesc('max_planned_end') + // $projectIssue = ProjectIssues::query() + // ->select('proyek_id','description','level_issue') + // ->get(); + // $ganttData = VersionGantt::query() + // ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id','calculation_type') // ->get(); - // $projectManager = User::whereId($result['pm_id'])->value('name'); - // $key =1; - // foreach($ganttData as $gantt) - // { - // $pStart =$plannedStart->where('version_gantt_id',$gantt['id'])->first(); - // $actStart =$startDate->where('version_gantt_id',$gantt['id'])->first(); - // $actEnd =$endDate->where('version_gantt_id',$gantt['id'])->first(); - // $pEnd =$plannedEnd->where('version_gantt_id',$gantt['id'])->first(); - // $matchingActivities = $overdueActivities->where('version_gantt_id', $gantt['id']); - // $matchingProjectComment = $projectComment->where('version_gantt_id', $gantt['id']); - // $usAtc = $utAct->where('version_gantt_id', $gantt['id']); - // $arr[] = - // [ - // 'gantt_id'=>$gantt['id'], - // 'projectManager'=>$projectManager, - // 'name_version'=>$gantt['name_version'], - // 'cost_to_complete'=>$gantt['cost_to_complete'], - // 'schedule' => [ - // 'plannedStart'=> $pStart['min_planned_start'], - // 'actual_start'=>$actStart['min_start'], - // 'plannedFinish'=>$pEnd['max_planned_end'], - // 'estimatedFinish'=>$actEnd['end_date'] - // ], - // 'manpower'=>$manCount, - // 'assigned'=>$usAtc->toArray(), - // 'actual'=>count($presence->toArray()), - // 'overdue_activities'=>$matchingActivities->toArray(), - // 'project_comment'=>$matchingProjectComment->toArray(), - // 'hierarchy'=>$finalData, - // 'proyek'=>$result, - // 'key'=>$key++ - // ]; + // $arr = []; + // foreach ($ganttData as $gantt) { + // $projectArr = []; + // $riskProject = []; + // $issueProject = []; + // foreach($projectData as $project) { + // if($project['id'] === $gantt['proyek_id']) { + // foreach ($projectRisk as $risk) { + // if ($risk['proyek_id'] === $project['id']) { + // $riskProject[] = [ + // 'level_risk' => $risk['level_risk'], + // 'preventive_risk' => $risk['preventive_risk'], + // 'description' => $risk['description'] + // ]; + // } + // } + // foreach ($projectIssue as $issue) { + // if ($issue['proyek_id'] === $project['id']) { + // $issueProject[] = [ + // 'level_issue' => $issue['level_issue'], + // 'description' => $issue['description'] + // ]; + // } + // } + // $projectArr[] = [ + // "project" => [ + // "id" => $project['id'], + // "pm_id" => $project['pm_id'], + // "nama" => $project['nama'], + // "kode_sortname" => $project['kode_sortname'], + // "budget_health" => $project['budget_health'], + // "calculation_status" => $project['calculation_status'], + // "mulai_proyek" => $project['mulai_proyek'], + // "akhir_proyek" => $project['akhir_proyek'], + // "rencana_biaya" => $project['rencana_biaya'], + // "company" => $project['company'], + // "scurve" => $project['scurve'], + // "project_risk" => $riskProject, + // "project_issues" => $issueProject + // ], + // ]; + // } + // } + + // $arr[] = [ + // "gantt" => [ + // "gantt_id" => $gantt['id'], + // 'proyek_id' => $gantt['proyek_id'], + // "name_version" => $gantt['name_version'], + // "hierarchy_ftth_id" => $gantt['hierarchy_ftth_id'], + // "cost_to_complete" => $gantt['cost_to_complete'], + // "calculation_type" => $gantt['calculation_type'], + // "project"=> $projectArr + // ], + // ]; // } - // return response()->json(['status'=>'success','code'=> 200,'data'=>$arr,'report_distribution'=>$reportsDistribution,'sCurve'=>$SCurve, 'count'=>count($arr)], 200); + // return response()->json(['status'=>'success','code'=> 200,'data'=>$projectArr, "total_project"=>count($arr)], 200); // } - // public function getParents(&$data, $id){ - // $ftth = HierarchyFtth::whereIn('id',$id)->get(); - // array_push($data, $ftth); - // if ($ftth->pluck('parent_id')->toArray()) { - // $this->getParents($data, $ftth->pluck('parent_id')->toArray()); + // public function getParents(&$data, $id) { + // $ftth = HierarchyFtth::find($id); + // array_push($data, $ftth); + // if ($ftth->parent_id) { + // $this->getParents($data, $ftth->parent_id); // } // } - public function invoke() - { - // Data Master - // Mengatur waktu awal bulan dan mengurangkan 1 tahun - $startDate = Carbon::now()->startOfMonth()->subYear()->format('Y-m-d'); - // Mengatur waktu saat ini dan mengurangkan 1 tahun - $endDate = Carbon::now()->subYear()->format('Y-m-d'); - $ganttData = VersionGantt::query() - ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id') - ->get(); + public function invoke() { + // Master Data $projectData = Project::query() - ->select("id","nama","kode_sortname","pm_id","budget_health","calculation_status","mulai_proyek","akhir_proyek","rencana_biaya","company","scurve") - ->get(); - // nested looping - $arr = []; - foreach($projectData as $project) { - $ganttForProject = []; - foreach ($ganttData as $gantt) { - if ($gantt['proyek_id'] === $project['id']) { - // Gantt - $ganttForProject[] = [ - "gantt_id" => $gantt['id'], - 'proyek_id' => $gantt['proyek_id'], - "name_version" => $gantt['name_version'], - "hierarchy_ftth_id" => $gantt['hierarchy_ftth_id'], - "cost_to_complete" => $gantt['cost_to_complete'], - ]; - // Activity - $activity = Activity::query() - ->select('id','name','proyek_id','version_gantt_id','type_activity','parent_id','kode_sortname','rencana_biaya','start_date','end_date','biaya_actual','persentase_bobot','persentase_progress','planned_start','planned_end','actual_start','actual_end') - ->whereNull('parent_id') - ->where([ - ["proyek_id", $project['id']], - ["version_gantt_id", $gantt['id']] - ]) - ->first(); - $actualStartExist = Activity::query() - ->where('version_gantt_id', $gantt['id']) - ->whereNotNull('actual_start') - ->exists(); - $actualEndExist = Activity::query() - ->where('version_gantt_id', $gantt['id']) - ->exists(); - $query = Activity::where('version_gantt_id', $gantt['id']); - - if ($actualStartExist) { - $startDate = $query->orderBy('actual_start')->value('start_date'); - } else { - $startDate = $query->orderBy('start_date')->value('start_date'); - } - if($actualEndExist) - { - $maxEndDate = $query->max('id'); - $endDate = $query->where('id',$maxEndDate)->first()->end_date; - } + ->select("id","nama","kode_sortname","pm_id","budget_health","calculation_status","mulai_proyek","akhir_proyek","rencana_biaya","company","scurve") + ->get(); + $projectRisk = ProjectRisks::query() + ->select('proyek_id','description','level_risk','preventive_risk') + ->get(); + $projectIssue = ProjectIssues::query() + ->select('proyek_id','description','level_issue') + ->get(); + $ganttData = VersionGantt::query() + ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id','calculation_type') + ->get(); - $plannedStart = Activity::where('version_gantt_id', $gantt['id']) - ->orderBy('planned_start') - ->value('planned_start'); - $plannedEnd = Activity::where('version_gantt_id', $gantt['id']) - ->orderByDesc('planned_end') - ->value('planned_end'); + // Nested looping - // SCurve - $req = (object)[ - 'project_id' => $project['id'], - 'gantt_id' => $gantt['id'], - 'period' => 'week', + $arr = []; + foreach ($ganttData as $gantt) { + $riskProject = []; + $issueProject = []; + foreach ($projectRisk as $risk) { + if ($risk['proyek_id'] === $gantt['proyek_id']) { + $riskProject[] = [ + 'level_risk' => $risk['level_risk'], + 'preventive_risk' => $risk['preventive_risk'], + 'description' => $risk['description'] ]; - $SCurve = MasterFunctionsHelper::getSCurveCarausell($req); - - // Overdue - $endDate = Activity::where('proyek_id', $project['id']) - ->orderByDesc('end_date') - ->value('end_date'); - $overdueActivities = Activity::query() - ->where([ - ['version_gantt_id', $gantt['id']], - ['persentase_progress', '!=', 100] - ]) - ->whereNotNull('parent_id') - ->whereDate('end_date','<=',$endDate) - ->orderBy('end_date', 'asc') - ->get(); - - // Manpower - $manCount = UserToProyek::where('proyek_id', $project['id'])->count(); - // Assigned - $assigned = UserToActivity::query() - ->select('assign_hr_to_activity.proyek_id', 'assign_hr_to_activity.user_id', 'm_activity.id', 'm_activity.name', 'm_activity.start_date', 'm_activity.end_date') - ->join('m_activity', 'm_activity.id', '=', 'assign_hr_to_activity.activity_id') - ->where('assign_hr_to_activity.version_gantt_id', $gantt['id']) - ->get(); - // Project Comment - $projectComment = ProjectComment::query() - ->select('m_users.name','m_users.username','m_project_comment.project_id','m_project_comment.gantt_id','m_project_comment.comment','m_project_comment.created_at') - ->join('m_users','m_project_comment.sender_id','m_users.id') - ->where([ - ['project_id',$project['id']], - ['gantt_id',$gantt['id']] - ]) - ->get(); - // Hierarchy - $finalData = []; - $ganttHierarchy = VersionGantt::find($gantt['id']); - if ($ganttHierarchy->hierarchy_ftth_id) { - $ftth = HierarchyFtth::find($ganttHierarchy->hierarchy_ftth_id); - array_push($finalData, $ftth); - if($ftth->parent_id){ - $this->getParents($finalData, $ftth->parent_id); - } - }else{ - $finalData = $finalData; - } - - $reports = DB::table('assign_material_to_activity as ama') - ->select('u.name', 'a.name as activity_name', 'ama.qty_planning', 'ram.qty as qty_real','rm.description as material_name', 'rm.uom as material_unit', - 'ram.lat', 'ram.lon', 'ram.description as report_notes', 'ram.report_date') - ->join('report_activity_material as ram', 'ram.assign_material_id', '=', 'ama.id') - ->join('m_req_material as rm', 'rm.id', '=', 'ama.material_id') - ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') - ->join('m_users as u', 'u.id', '=', 'ram.user_id') - ->where('ama.proyek_id', '=', $project['id']) - ->whereNotNull('ram.lat') - ->whereBetween('ram.report_date', [$startDate, $endDate]); } } - $projectManager = User::where('id', $project['pm_id'])->value('name'); + foreach ($projectIssue as $issue) { + if ($issue['proyek_id'] === $gantt['proyek_id']) { + $issueProject[] = [ + 'level_issue' => $issue['level_issue'], + 'description' => $issue['description'] + ]; + } + } - $arr[]= [ - "project"=> [ - "id"=>$project['id'], - "pm_id"=>$project['pm_id'], - "nama"=>$project['nama'], - "kode_sortname"=>$project['kode_sortname'], - "budget_health"=>$project['budget_health'], - "calculation_status"=>$project['calculation_status'], - "mulai_proyek"=>$project['mulai_proyek'], - "akhir_proyek"=>$project['akhir_proyek'], - "rencana_biaya"=>$project['rencana_biaya'], - "company"=>$project['company'], - "scurve"=>$project['scurve'], - "gantt"=>$ganttForProject - ], - "hierarchy"=>$finalData, - "manpower"=>$manCount, - "assigned"=>$assigned, - "actual"=>0, - "project_comment"=>$projectComment, - "project_manager"=> $projectManager, - "activity" => [ - "data" => $activity, - "start_date"=>$startDate, - "end_date"=>$endDate, - "planned_start"=>$plannedStart, - "planned_end"=>$plannedEnd + $arr[$gantt['proyek_id']][] = [ + "gantt" => [ + "gantt_id" => $gantt['id'], + 'proyek_id' => $gantt['proyek_id'], + "name_version" => $gantt['name_version'], + "hierarchy_ftth_id" => $gantt['hierarchy_ftth_id'], + "cost_to_complete" => $gantt['cost_to_complete'], + "calculation_type" => $gantt['calculation_type'], ], - "report_distribution"=>$reports, - "overdueActivities"=>$overdueActivities, - "SCurve"=>$SCurve + "project_risk" => $riskProject, + "project_issue"=>$issueProject ]; } - return response()->json(['status'=>'success','code'=> 200,'data'=>$arr, "count"=>count($arr)], 200); - } - public function getParents(&$data, $id){ - $ftth = HierarchyFtth::find($id); - array_push($data, $ftth); - if ($ftth->parent_id) { - $this->getParents($data, $ftth->parent_id); + foreach($projectData as $project) { + $projectManager = User::where('id', $project['pm_id'])->value('name'); + $arr[$project['id']][] = [ + "project" => [ + "id" => $project['id'], + "pm_id" => $project['pm_id'], + "nama" => $project['nama'], + "kode_sortname" => $project['kode_sortname'], + "budget_health" => $project['budget_health'], + "calculation_status" => $project['calculation_status'], + "mulai_proyek" => $project['mulai_proyek'], + "akhir_proyek" => $project['akhir_proyek'], + "rencana_biaya" => $project['rencana_biaya'], + "company" => $project['company'], + "project_manager" => $projectManager, + "scurve" => $project['scurve'] + ], + ]; } + + return response()->json(['status'=>'success','code'=> 200,'data'=>$arr, "total_project"=>count($arr)], 200); } } From c3ebdfc5eccae8ee1ca456b221af7b38944b01af Mon Sep 17 00:00:00 2001 From: wahyuun Date: Fri, 1 Dec 2023 13:58:51 +0700 Subject: [PATCH 012/155] update response carousel --- .../ProjectCarausellController.php | 129 +++--------------- 1 file changed, 17 insertions(+), 112 deletions(-) diff --git a/app/Http/Controllers/ProjectCarausellController.php b/app/Http/Controllers/ProjectCarausellController.php index 361b8b1..2850318 100644 --- a/app/Http/Controllers/ProjectCarausellController.php +++ b/app/Http/Controllers/ProjectCarausellController.php @@ -11,88 +11,6 @@ use App\Models\{ }; class ProjectCarausellController extends Controller { - // public function invoke() { - // // Master Data - // $projectData = Project::query() - // ->select("id","nama","kode_sortname","pm_id","budget_health","calculation_status","mulai_proyek","akhir_proyek","rencana_biaya","company","scurve") - // ->get(); - // $projectRisk = ProjectRisks::query() - // ->select('proyek_id','description','level_risk','preventive_risk') - // ->get(); - // $projectIssue = ProjectIssues::query() - // ->select('proyek_id','description','level_issue') - // ->get(); - // $ganttData = VersionGantt::query() - // ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id','calculation_type') - // ->get(); - - // $arr = []; - // foreach ($ganttData as $gantt) { - // $projectArr = []; - // $riskProject = []; - // $issueProject = []; - // foreach($projectData as $project) { - // if($project['id'] === $gantt['proyek_id']) { - // foreach ($projectRisk as $risk) { - // if ($risk['proyek_id'] === $project['id']) { - // $riskProject[] = [ - // 'level_risk' => $risk['level_risk'], - // 'preventive_risk' => $risk['preventive_risk'], - // 'description' => $risk['description'] - // ]; - // } - // } - // foreach ($projectIssue as $issue) { - // if ($issue['proyek_id'] === $project['id']) { - // $issueProject[] = [ - // 'level_issue' => $issue['level_issue'], - // 'description' => $issue['description'] - // ]; - // } - // } - // $projectArr[] = [ - // "project" => [ - // "id" => $project['id'], - // "pm_id" => $project['pm_id'], - // "nama" => $project['nama'], - // "kode_sortname" => $project['kode_sortname'], - // "budget_health" => $project['budget_health'], - // "calculation_status" => $project['calculation_status'], - // "mulai_proyek" => $project['mulai_proyek'], - // "akhir_proyek" => $project['akhir_proyek'], - // "rencana_biaya" => $project['rencana_biaya'], - // "company" => $project['company'], - // "scurve" => $project['scurve'], - // "project_risk" => $riskProject, - // "project_issues" => $issueProject - // ], - // ]; - // } - // } - - // $arr[] = [ - // "gantt" => [ - // "gantt_id" => $gantt['id'], - // 'proyek_id' => $gantt['proyek_id'], - // "name_version" => $gantt['name_version'], - // "hierarchy_ftth_id" => $gantt['hierarchy_ftth_id'], - // "cost_to_complete" => $gantt['cost_to_complete'], - // "calculation_type" => $gantt['calculation_type'], - // "project"=> $projectArr - // ], - // ]; - // } - // return response()->json(['status'=>'success','code'=> 200,'data'=>$projectArr, "total_project"=>count($arr)], 200); - // } - - // public function getParents(&$data, $id) { - // $ftth = HierarchyFtth::find($id); - // array_push($data, $ftth); - // if ($ftth->parent_id) { - // $this->getParents($data, $ftth->parent_id); - // } - // } - public function invoke() { // Master Data $projectData = Project::query() @@ -104,18 +22,13 @@ class ProjectCarausellController extends Controller $projectIssue = ProjectIssues::query() ->select('proyek_id','description','level_issue') ->get(); - $ganttData = VersionGantt::query() - ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id','calculation_type') - ->get(); - - // Nested looping $arr = []; - foreach ($ganttData as $gantt) { + foreach($projectData as $project) { $riskProject = []; $issueProject = []; foreach ($projectRisk as $risk) { - if ($risk['proyek_id'] === $gantt['proyek_id']) { + if ($risk['proyek_id'] === $project['id']) { $riskProject[] = [ 'level_risk' => $risk['level_risk'], 'preventive_risk' => $risk['preventive_risk'], @@ -123,33 +36,21 @@ class ProjectCarausellController extends Controller ]; } } - foreach ($projectIssue as $issue) { - if ($issue['proyek_id'] === $gantt['proyek_id']) { + if ($issue['proyek_id'] === $project['id']) { $issueProject[] = [ 'level_issue' => $issue['level_issue'], 'description' => $issue['description'] ]; } } - - $arr[$gantt['proyek_id']][] = [ - "gantt" => [ - "gantt_id" => $gantt['id'], - 'proyek_id' => $gantt['proyek_id'], - "name_version" => $gantt['name_version'], - "hierarchy_ftth_id" => $gantt['hierarchy_ftth_id'], - "cost_to_complete" => $gantt['cost_to_complete'], - "calculation_type" => $gantt['calculation_type'], - ], - "project_risk" => $riskProject, - "project_issue"=>$issueProject - ]; - } - - foreach($projectData as $project) { + $ganttData = VersionGantt::query() + ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id','calculation_type') + ->where('proyek_id',$project['id']) + ->orderByDesc('id') + ->first(); $projectManager = User::where('id', $project['pm_id'])->value('name'); - $arr[$project['id']][] = [ + $arr[]= [ "project" => [ "id" => $project['id'], "pm_id" => $project['pm_id'], @@ -161,12 +62,16 @@ class ProjectCarausellController extends Controller "akhir_proyek" => $project['akhir_proyek'], "rencana_biaya" => $project['rencana_biaya'], "company" => $project['company'], - "project_manager" => $projectManager, - "scurve" => $project['scurve'] + "scurve" => $project['scurve'], + "project_risk" => $riskProject, + "project_issues" => $issueProject ], + "project_manager" => $projectManager, + "project_risk" => $riskProject, + "project_issue" => $projectIssue, + "gantt"=> $ganttData ]; } - - return response()->json(['status'=>'success','code'=> 200,'data'=>$arr, "total_project"=>count($arr)], 200); + return response()->json(['status'=>'success','code'=> 200,'data'=> $arr, "total_project"=>count($arr)], 200); } } From de9b52592d323fa9019768727b54b231b92f62ab Mon Sep 17 00:00:00 2001 From: ibnu Date: Sun, 3 Dec 2023 03:47:26 +0700 Subject: [PATCH 013/155] update calculate curva with day --- app/Helpers/MasterFunctionsHelper.php | 404 ++++++-------------- app/Http/Controllers/ActivityController.php | 1 + rest-client.http | 21 +- 3 files changed, 132 insertions(+), 294 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index f1e9058..c43d887 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -165,41 +165,26 @@ class MasterFunctionsHelper public function calculateProgressBasedOnReportMaterialOld($keyGantt) { DB::enableQueryLog(); - $dataFinal = []; $dataPayload = []; $dataPayload['period'] = 'week'; $totalACWP = 0; $totalBCWP = 0; $tempPercentage = []; - $dataProject = Project::find($keyGantt['proyek_id']); $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->first(); if (isset($dataPayload['end_date']) && $dataPayload['end_date'] > $dataProject->akhir_proyek) { $dataPayload['end_date'] = $dataProject->akhir_proyek; } - if ($dataHeader) { $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); } else { $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); } - if (!Activity::where("version_gantt_id", $keyGantt['id'])->first()) return $dataFinal; - - $alreadyHasReport = DB::table('report_activity_material as a') - ->select('a.id') - ->join('m_activity as b', 'b.id', '=', 'a.activity_id') - ->where('b.version_gantt_id', '=', $keyGantt['id']) - ->exists(); - // note : delete this - // if(!$alreadyHasReport) - // return $dataFinal; - $minDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('start_date')->first(); - - $begin = new \DateTime($minDate . ' Monday'); + $begin = new \DateTime($minDate); $begin->modify('last Monday'); if (isset($dataPayload['end_date'])) { $maxDate = $dataPayload['end_date']; @@ -226,7 +211,6 @@ class MasterFunctionsHelper $interval = new \DateInterval('P7D'); } $period = new \DatePeriod($begin, $interval, $end); - $arr_ActualM = []; $tempDate = []; $tempPercentagePlan = []; @@ -234,23 +218,12 @@ class MasterFunctionsHelper $tempPercentageReal = []; $tempTtlPercentPlan = 0; $tempTtlPercentActual = 0; - $currentACWP = 0; $currentBCWP = 0; - foreach ($period as $dt) { $minSevenDays = new \Datetime($dt->format("Y-m-d")); $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); $tempDate[] = array($dt->format("Y-m-d")); - // $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('a.version_gantt_id', '=', $keyGantt['id']) - // ->whereDate('ama.plan_date', '<=',$dt->format("Y-m-d")) - // ->whereDate('ama.plan_date', '>', $minSevenDays) - // ->get(); - $activities = DB::table('m_activity AS a') ->join('assign_material_to_activity AS amta', 'amta.activity_id', '=', 'a.id') ->where('a.type_activity', 'task') @@ -259,7 +232,6 @@ class MasterFunctionsHelper ->whereDate('amta.plan_date', '<=', $dt->format("Y-m-d")) ->whereDate('amta.plan_date', '>', $minSevenDays) ->select('a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress', 'a.id'); - $dataPlanM = DB::table('m_activity AS a') ->join('assign_hr_to_activity AS ahta', 'ahta.activity_id', '=', 'a.id') ->where('a.type_activity', 'task') @@ -270,7 +242,6 @@ class MasterFunctionsHelper ->select('a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress', 'a.id') ->union($activities) ->get(); - $dataActualM = DB::table('report_activity_material as ram') ->select('ram.activity_id', 'ram.qty', 'ram.report_date', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') ->join('m_activity as a', 'a.id', '=', 'ram.activity_id') @@ -284,7 +255,6 @@ class MasterFunctionsHelper $sumPercentagePlan = 0; $totalACWP = isset($totalACWP) ? $totalACWP : 0; $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; - foreach ($dataPlanM as $keyPlanM) { // $sumVolPlan = DB::table(function ($query) use ($keyGantt) { // $query->select('a.*') @@ -309,9 +279,21 @@ class MasterFunctionsHelper ->where('activity_id', '=', $keyPlanM->id) ->groupBy('activity_id') ->first(); - $weekCount = $keyPlanM->duration / $keyPlanM->duration; - $weeklyPlan = $weekCount > 0 ? $sumVolPlan->ttl_qty_plan / $weekCount : 0; - $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + if($keyPlanM->duration){ + $weekCount = $keyPlanM->duration / 7; + $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; + // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + // $bobotHari = $keyPlanM->bobot_planning / $keyPlanM->duration; + }else{ + // $weeklyProgress = 0; + $weekCount = 1 / 7; + $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; + // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + + } + // $weeklyPlan = $weekCount > 0 ? $keyPlanM->bobot_planning / $weekCount : 0; // $weeklyProgress = $weeklyPlan * $keyPlanM->bobot_planning; $dataTempPlan[$x]['activity_id'] = $keyPlanM->id; @@ -333,7 +315,6 @@ class MasterFunctionsHelper } $x++; } - $w = 0; $dataTempReport = []; $sumPercentageActual = 0; @@ -384,8 +365,6 @@ class MasterFunctionsHelper // $sumPercentageActual+=($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; // } // } - - $totalACWP += $keyActualM->duration > 0 ? $keyActualM->biaya_actual / $keyActualM->duration : 0; } catch (\DivisionByZeroError $e) { return response()->json(['message' => $e->getMessage()]); @@ -393,7 +372,6 @@ class MasterFunctionsHelper $dataTempReport[$w]['totalacwp'] = $totalACWP; $w++; } - $arr_ActualM[] = array( 'date' => $dt->format("Y-m-d"), 'percentPlan' => $sumPercentagePlan, @@ -401,42 +379,30 @@ class MasterFunctionsHelper 'plan' => $dataTempPlan, 'actual' => $dataTempReport, ); + $today = new DateTime(); + $date = new DateTime($dt->format("Y-m-d")); if (isset($dataPayload['period']) && $dataPayload['period'] == 'week') { $tempTtlPercentPlan += $sumPercentagePlan; $tempTtlPercentActual += $sumPercentageActual; - - // if($tempTtlPercentPlan >= 100 || $tempTtlPercentActual >= $keyGantt['progress'];){ - // if($tempTtlPercentActual >= 100) - // $tempTtlPercentActual = 100; - // if($tempTtlPercentPlan >= 100) - // $tempTtlPercentPlan = 100; - - // if($tempTtlPercentActual >= $keyGantt['progress']) - // $tempTtlPercentActual = $keyGantt['progress']; - // todo - // if ($tempTtlPercentPlan >= 100) - // $tempTtlPercentPlan = 100; - // $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual - - // } - $currentACWP += $totalACWP; $currentBCWP += $totalBCWP; - $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); $tempPercentagePlan[] = round($tempTtlPercentPlan, 2); $tempPercentagePlanWhr[] = ["weekly period", $tempPercentagePlan]; + if ($date < $today) { $tempPercentageReal[] = round($tempTtlPercentActual, 2); + } if ($tempTtlPercentPlan >= 100 && $tempTtlPercentActual >= 100) { break; } } else { $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); $tempPercentagePlan[] = round($sumPercentagePlan, 2); + if ($date < $today) { $tempPercentageReal[] = round($sumPercentageActual, 2); + } } } - try { if (round($totalACWP, 0) > $totalRencanaBudget) { $estimatedCost = round($totalACWP, 0) + 0; @@ -451,14 +417,12 @@ class MasterFunctionsHelper ]); } $estimatedCost = $totalACWP > $totalRencanaBudget ? $totalACWP : $totalRencanaBudget; - $costDeviation = $totalRencanaBudget - $estimatedCost; if ($costDeviation > 0) { $potential = "SAVING"; } else { $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; - } - + } $lastReal = $tempPercentageReal[count($tempPercentageReal) - 1]; $totalBCWP = $lastReal * $dataProject->rencana_biaya / 100; $dataResponse = array( @@ -478,13 +442,11 @@ class MasterFunctionsHelper "potential" => $potential, ) ); - $dataFinal[] = array( "proyek_name" => $dataProject->nama, "data" => $dataResponse, "gantt" => $keyGantt ); - return $dataFinal; } @@ -517,14 +479,14 @@ class MasterFunctionsHelper $minDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('start_date')->first(); $begin = new \DateTime($minDate); - $begin->modify('last Monday'); + $begin = $begin->modify('-1 day'); if (isset($dataPayload['end_date'])) { $maxDate = $dataPayload['end_date']; $end = new \DateTime($maxDate . ' Friday'); - $end->modify('next Friday'); - $end->modify('next Friday'); + // $end->modify('next Friday'); + // $end->modify('next Friday'); /* $interval = \DateInterval::createFromDateString('1 day'); */// should be using this but its bugged - $interval = new \DateInterval('P7D'); + $interval = new \DateInterval('P1D'); } else { $actualMaxDate = DB::table('assign_material_to_activity as ama') ->where("ama.proyek_id", $keyGantt['proyek_id']) @@ -538,9 +500,9 @@ class MasterFunctionsHelper ->max("a.planned_end"); // plan date overlapped with assign_material_to_activity's, it should be m_activity' $maxDate = max(new \DateTime($plannedMaxDate), new \DateTime($actualMaxDate)); $end = new \DateTime($maxDate->format('Y-m-d') . ' Friday'); - $end->modify('next Friday'); - $end->modify('next Friday'); - $interval = new \DateInterval('P7D'); + // $end->modify('next Friday'); + // $end->modify('next Friday'); + $interval = new \DateInterval('P1D'); } $period = new \DatePeriod($begin, $interval, $end); @@ -554,245 +516,113 @@ class MasterFunctionsHelper $currentACWP = 0; $currentBCWP = 0; - + $dataActivityPlanDate = []; + $progressPlanKomulatifWeek = []; + $progressActualKomulatifWeek = []; + $dateWeek = []; + $tmpProgressPlanWeek = 0; + $tmpProgressActualWeek = 0; foreach ($period as $dt) { - $minSevenDays = new \Datetime($dt->format("Y-m-d")); - $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); + $loopDay = $dt->format("Y-m-d"); + //new \Datetime($dt->format("Y-m-d")); + // $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); $tempDate[] = array($dt->format("Y-m-d")); - $activities = DB::table('m_activity AS a') - ->join('assign_material_to_activity AS amta', 'amta.activity_id', '=', 'a.id') - ->where('a.type_activity', 'task') - ->where('a.bobot_planning', '>', 0) - ->where('a.version_gantt_id', $keyGantt['id']) - ->whereDate('amta.plan_date', '<=', $dt->format("Y-m-d")) - ->whereDate('amta.plan_date', '>', $minSevenDays) - ->select('a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress', 'a.id'); - - $dataPlanM = DB::table('m_activity AS a') - ->join('assign_hr_to_activity AS ahta', 'ahta.activity_id', '=', 'a.id') - ->where('a.type_activity', 'task') - ->where('a.bobot_planning', '>', 0) - ->where('a.version_gantt_id', $keyGantt['id']) - ->whereDate('a.start_date', '<=', $dt->format("Y-m-d")) - ->whereDate('a.start_date', '>', $minSevenDays) - ->select('a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress', 'a.id') - ->union($activities) - ->get(); + $dataPlanM = DB::table('m_activity') + ->where('type_activity', 'task') + ->where('bobot_planning', '>', 0) + ->where('version_gantt_id', $keyGantt['id']) + ->whereDate('planned_start', '<=', $loopDay) + ->whereDate('planned_end', '>=', $loopDay) + ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id') + ->get(); $dataActualM = DB::table('report_activity_material as ram') - ->select('ram.activity_id', 'ram.qty', 'ram.report_date', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') - ->join('m_activity as a', 'a.id', '=', 'ram.activity_id') - ->where('a.version_gantt_id', '=', $keyGantt['id']) - ->where('a.proyek_id', '=', $keyGantt['proyek_id']) - ->whereDate('ram.report_date', '<=', $dt->format("Y-m-d")) - ->whereDate('ram.report_date', '>', $minSevenDays) + ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') + ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', + DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), + DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), + DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity') + ) + ->where('ram.report_date', $loopDay) + ->where('ma.version_gantt_id', $keyGantt['id']) ->get(); - $dataTempPlan = []; - $x = 0; - $sumPercentagePlan = 0; - $totalACWP = isset($totalACWP) ? $totalACWP : 0; - $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; - - foreach ($dataPlanM as $keyPlanM) { - // $sumVolPlan = DB::table(function ($query) use ($keyGantt) { - // $query->select('a.*') - // ->from('m_activity AS a') - // ->join('assign_material_to_activity as amta', 'amta.activity_id', '=', 'a.id') - // ->where('a.type_activity', 'task') - // ->where('a.bobot_planning', '>', 0) - // ->where('a.version_gantt_id', $keyGantt['id']) - // ->unionAll(function ($query) use ($keyGantt) { - // $query->select('a.*') - // ->from('m_activity AS a') - // ->join('assign_hr_to_activity as ahta', 'ahta.activity_id', '=', 'a.id') - // ->where('a.type_activity', 'task') - // ->where('a.bobot_planning', '>', 0) - // ->where('a.version_gantt_id', $keyGantt['id']); - // }) - // ->orderBy('id', 'asc'); - // }, 'subquery') - // ->sum('bobot_planning'); - $sumVolPlan = DB::table('assign_material_to_activity') - ->select('activity_id', DB::raw('SUM(qty_planning) as ttl_qty_plan')) - ->where('activity_id', '=', $keyPlanM->id) - ->groupBy('activity_id') - ->first(); - if($keyPlanM->duration){ - $weekCount = $keyPlanM->duration / 7; - $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; - // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; - $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; - // $bobotHari = $keyPlanM->bobot_planning / $keyPlanM->duration; - }else{ - // $weeklyProgress = 0; - $weekCount = 1 / 7; - $weeklyPlan = $weekCount >= 1 ? $sumVolPlan->ttl_qty_plan / $weekCount : $sumVolPlan->ttl_qty_plan / $weekCount / 7; - // $weeklyProgress = $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; - $weeklyProgress = $weeklyPlan / $sumVolPlan->ttl_qty_plan * $keyPlanM->bobot_planning; + + $dataActivityPlan = []; + $dataActivityActual = []; + $today = new DateTime(); + if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ + $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); + if (new \DateTime($loopDay) < $today) { + // $tempPercentageReal[] = round($tempTtlPercentActual, 2); + $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); } - - // $weeklyPlan = $weekCount > 0 ? $keyPlanM->bobot_planning / $weekCount : 0; - // $weeklyProgress = $weeklyPlan * $keyPlanM->bobot_planning; - $dataTempPlan[$x]['activity_id'] = $keyPlanM->id; - $dataTempPlan[$x]['bobot_planning'] = $keyPlanM->bobot_planning; - $dataTempPlan[$x]['ttl_plan'] = $sumVolPlan; - $dataTempPlan[$x]['biaya_actual'] = $keyPlanM->biaya_actual; - $dataTempPlan[$x]['duration'] = $keyPlanM->duration; - $dataTempPlan[$x]['persentase_progress'] = $keyPlanM->persentase_progress; - try { - $dataTempPlan[$x]['percentage'] = $keyPlanM->bobot_planning; - $sumPercentagePlan += $weeklyProgress; - if (isset($keyPlanM->duration) && $keyPlanM->duration > 0) - $totalBCWP += (((($keyPlanM->persentase_progress * $keyPlanM->bobot_planning) / 100) / $keyPlanM->duration) * $totalRencanaBudget) / 100; - else - $totalBCWP = 0; - $dataTempPlan[$x]['totalBCWP'] = $totalBCWP; - } catch (\DivisionByZeroError $e) { - return response()->json(['message' => $e->getMessage()]); - } - $x++; + $dateWeek[] = [$loopDay]; + // $tmpProgressPlanWeek = 0; + // $tmpProgressActualWeek = 0; } - - $w = 0; - $dataTempReport = []; - $sumPercentageActual = 0; - foreach ($dataActualM as $keyActualM) { - $sumVolActual = DB::table('assign_material_to_activity') - ->select('activity_id', DB::raw('SUM(qty_planning) as ttl_qty_plan')) - ->where('activity_id', '=', $keyActualM->activity_id) - ->groupBy('activity_id') - ->first(); - $sumReportActual = DB::table('report_activity_material') - ->where('activity_id', $keyActualM->activity_id) - ->sum('qty'); - $reportCount = DB::table('report_activity_material')->where('activity_id', '=', $keyActualM->activity_id)->count(); - $dataTempReport[$w]['activity_id'] = $keyActualM->activity_id; - $dataTempReport[$w]['qty'] = $keyActualM->qty; - $dataTempReport[$w]['report_date'] = $keyActualM->report_date; - $dataTempReport[$w]['bobot_planning'] = $keyActualM->bobot_planning; - $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; - try { - // assign_material_to_activity - $checkStatusActivity = DB::table('assign_material_to_activity') - ->select('activity_id', 'status_activity') - ->where('activity_id', '=', $keyActualM->activity_id) - ->orderBy('status_activity', 'ASC') - ->first(); - $dataTempReport[$w]['percentage'] = ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; - // $sumPercentageActual+=($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; - // if($keyActualM->qty/$sumVolActual->ttl_qty_plan >= 1){ - if ($checkStatusActivity->status_activity == 'done') { - $sumPercentageActual += $keyActualM->bobot_planning / $reportCount; - // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; - } else { - if ($keyActualM->qty / $sumVolActual->ttl_qty_plan >= 1 || (int) $sumVolActual->ttl_qty_plan == (int) $sumReportActual) { - $sumPercentageActual += (($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning) * (95 / 100); - // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; - } else { - $sumPercentageActual += ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; - // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; - } - } - // }else { - // if($checkStatusActivity->status_activity == 'done'){ - // $sumPercentageActual+=($keyActualM->qty/$keyActualM->qty)*$keyActualM->bobot_planning; - // }else{ - // $sumPercentageActual+=($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; - // } - // } - - - $totalACWP += $keyActualM->duration > 0 ? $keyActualM->biaya_actual / $keyActualM->duration : 0; - } catch (\DivisionByZeroError $e) { - return response()->json(['message' => $e->getMessage()]); - } - $dataTempReport[$w]['totalacwp'] = $totalACWP; - $w++; + // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; + foreach ($dataPlanM as $keyPlanM) { + # hitung untuk persentase progress planning + $dataActivityPlan[] = array( + 'progressPlanDay' => $keyPlanM->bobot_planning / $keyPlanM->duration, + 'name' => $keyPlanM->name, + 'bobot_p' => $keyPlanM->bobot_planning, + 'duration' => $keyPlanM->duration + ); + $tmpProgressPlanWeek += $keyPlanM->bobot_planning / $keyPlanM->duration; } - $arr_ActualM[] = array( - 'date' => $dt->format("Y-m-d"), - 'percentPlan' => $sumPercentagePlan, - 'percentActual' => $sumPercentageActual, - 'plan' => $dataTempPlan, - 'actual' => $dataTempReport, - ); - $today = new DateTime(); - $date = new DateTime($dt->format("Y-m-d")); - if (isset($dataPayload['period']) && $dataPayload['period'] == 'week') { - $tempTtlPercentPlan += $sumPercentagePlan; - $tempTtlPercentActual += $sumPercentageActual; - - $currentACWP += $totalACWP; - $currentBCWP += $totalBCWP; - - $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); - $tempPercentagePlan[] = round($tempTtlPercentPlan, 2); - $tempPercentagePlanWhr[] = ["weekly period", $tempPercentagePlan]; - if ($date < $today) { - $tempPercentageReal[] = round($tempTtlPercentActual, 2); + // hitung progress actual + foreach ($dataActualM as $keyActualM) { + # hitung untuk persentase progress actual + // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; + if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; + }else{ + $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; } - if ($tempTtlPercentPlan >= 100 && $tempTtlPercentActual >= 100) { - break; + if($keyActualM->status_activity == 'done'){ + $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; } - } else { - $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); - $tempPercentagePlan[] = round($sumPercentagePlan, 2); - if ($date < $today) { - $tempPercentageReal[] = round($sumPercentageActual, 2); + else{ + $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; } + $dataActivityActual[] = array( + 'progressActualDay' => $progressActualWeek, + 'qty_act' => $keyActualM->qty_actual, + 'bobot_p' => $keyActualM->bobot_planning, + 'qty_plan' => $keyActualM->qty_plan, + 'status_activity' => $keyActualM->status_activity, + 'sum_qty_actual' => $keyActualM->sum_qty_actual, + 'name' => $keyActualM->name + ); + + $tmpProgressActualWeek += $progressActualWeek; } - } - try { - if (round($totalACWP, 0) > $totalRencanaBudget) { - $estimatedCost = round($totalACWP, 0) + 0; - } else { - $estimatedCost = ($totalRencanaBudget + 0); - } - } catch (\DivisionByZeroError $e) { - return response()->json([ - 'message' => $e->getMessage(), - "line" => 566, - 'gantt' => $keyGantt, - ]); + $dataActivityPlanDate[] = array( + "date" => $loopDay, + "statusWeek" => new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday') ? true : false, + "activity-plan" => $dataActivityPlan, + "activity-actual" => $dataActivityActual, + "tmpProgressActualWeek" => $tmpProgressActualWeek, + "progressPlanWeek" => $tmpProgressPlanWeek + ); + } - $estimatedCost = $totalACWP > $totalRencanaBudget ? $totalACWP : $totalRencanaBudget; - - $costDeviation = $totalRencanaBudget - $estimatedCost; - if ($costDeviation > 0) { - $potential = "SAVING"; - } else { - $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; - } - $lastReal = $tempPercentageReal[count($tempPercentageReal) - 1]; - $totalBCWP = $lastReal * $dataProject->rencana_biaya / 100; - $dataResponse = array( - "date" => $tempDate, - "percentage" => $tempPercentage, - "percentagePlan" => $tempPercentagePlan, - "percentageReal" => $tempPercentageReal, - "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" => $potential, - ) - ); $dataFinal[] = array( + // "date" => $dateWeek, "proyek_name" => $dataProject->nama, - "data" => $dataResponse, + "data" => ["date" => $dateWeek, + "percentagePlan" => $progressPlanKomulatifWeek, + "percentageActual" => $progressActualKomulatifWeek, + "data_details" => $dataActivityPlanDate + ], + + "gantt" => $keyGantt ); diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index eabfcc6..c2a8223 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -604,6 +604,7 @@ class ActivityController extends Controller $activityToUpdate = $activity->firstWhere('id', $entity['data']['id']); $entity['data']['name'] = $entity['data']['text']; $entity['data']['persentase_progress'] = $entity['data']['progress'] * 100; + $entity['data']['type_activity'] = $entity['data']['type']; if (isset($entity['data']['rencana_biaya'])) { $entity['data']['rencana_biaya'] = str_replace(",", ".", $entity['data']['rencana_biaya']); } diff --git a/rest-client.http b/rest-client.http index 6abe9ab..932e596 100644 --- a/rest-client.http +++ b/rest-client.http @@ -1,4 +1,4 @@ -@token = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9iYWNrZW5kLnRlc3RcL2FwaVwvbG9naW4iLCJpYXQiOjE3MDA0NTA1ODYsImV4cCI6MTcwMTA1NTM4NiwibmJmIjoxNzAwNDUwNTg2LCJqdGkiOiJack9MMU04UGdKWGkwTUU1Iiwic3ViIjoxLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.fyg6CyiCAcX3GD4iSy8urkHpZEJ4mnXSXQc4NKC8U9A +@token = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9iYWNrZW5kLnRlc3RcL2FwaVwvbG9naW4iLCJpYXQiOjE3MDEzNzMzNzQsImV4cCI6MTcwMTk3ODE3NCwibmJmIjoxNzAxMzczMzc0LCJqdGkiOiJhbkJWOHIwUDZndFRXZk5KIiwic3ViIjoxNzg4LCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.QCiXq-62da7Sdk7sEb_J0apEij_R6IQgZVYG9iL6M8g @tokenS = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9hZHctYXBpLm9zcHJvLmlkXC9hcGlcL2xvZ2luIiwiaWF0IjoxNjkxNTcyMTIwLCJleHAiOjE2OTIxNzY5MjAsIm5iZiI6MTY5MTU3MjEyMCwianRpIjoiVUdqbnhLRVdlZzYyTTBnayIsInN1YiI6MSwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.5QqK0dLW5jzbVOkSCSW0mFo0K7ycGOBW9NCG_2Zldm4 @@ -18,8 +18,8 @@ POST {{hostname}}/login content-type: application/json { - "username": "admin", - "password": "1nt3gr4s14" + "username": "testing", + "password": "testing123" } ###### Tools Req @@ -835,8 +835,9 @@ POST {{hostname}}/project/s-curve-command-test Authorization: Bearer {{token}} content-type: application/json - {"period":"week","project_id":"129","gantt_id":"862"} -### {"period":"week","project_id":"129","gantt_id":"862"} +# {"period":"week","project_id":"137","gantt_id":"916"} +# {"period":"week","project_id":"129","gantt_id":"862"} +{"period":"week","project_id":"140","gantt_id":"1103"} ### POST {{hostname}}/project/calculate-s-curve @@ -851,8 +852,14 @@ POST {{hostname}}/project/get-s-curve Authorization: Bearer {{token}} content-type: application/json -{"period":"week","project_id":"129","gantt_id":"800"} -### {"period":"week","project_id":"135","gantt_id":"891"} +{"project_id":"164","gantt_id":"973","period":"week"} +### {"period":"week","project_id":"129","gantt_id":"800"} + +####### +GET {{hostname}}/activity/s-curve/137/892 +Authorization: Bearer {{token}} +content-type: application/json + ### GET https://adw-api.ospro.id/api/request-material/get-material-integration?name=c From 8f084901089d2704d205e0286272565d234f30bf Mon Sep 17 00:00:00 2001 From: ibnu Date: Sun, 3 Dec 2023 07:02:51 +0700 Subject: [PATCH 014/155] update logic duration 0 --- app/Helpers/MasterFunctionsHelper.php | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index c43d887..a507ec2 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -534,7 +534,7 @@ class MasterFunctionsHelper ->where('version_gantt_id', $keyGantt['id']) ->whereDate('planned_start', '<=', $loopDay) ->whereDate('planned_end', '>=', $loopDay) - ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id') + ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') ->get(); $dataActualM = DB::table('report_activity_material as ram') @@ -558,20 +558,29 @@ class MasterFunctionsHelper // $tempPercentageReal[] = round($tempTtlPercentActual, 2); $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); } - $dateWeek[] = [$loopDay]; - // $tmpProgressPlanWeek = 0; - // $tmpProgressActualWeek = 0; + $dateWeek[] = [$loopDay]; } // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; foreach ($dataPlanM as $keyPlanM) { # hitung untuk persentase progress planning + if($keyPlanM->duration == 0){ + $duration = 2; + } + // $startPlan = new DateTime($keyPlanM->planned_start); + // $endPlan = new DateTime($keyPlanM->planned_end); + // $interval = $startPlan->diff($endPlan); + + // // Mengambil hasil selisih hari + // $duration = $interval->days; + + $progressPlanWeek = $keyPlanM->bobot_planning / $duration; $dataActivityPlan[] = array( - 'progressPlanDay' => $keyPlanM->bobot_planning / $keyPlanM->duration, + 'progressPlanDay' => $progressPlanWeek, 'name' => $keyPlanM->name, 'bobot_p' => $keyPlanM->bobot_planning, 'duration' => $keyPlanM->duration ); - $tmpProgressPlanWeek += $keyPlanM->bobot_planning / $keyPlanM->duration; + $tmpProgressPlanWeek += $progressPlanWeek; } // hitung progress actual @@ -618,7 +627,7 @@ class MasterFunctionsHelper "proyek_name" => $dataProject->nama, "data" => ["date" => $dateWeek, "percentagePlan" => $progressPlanKomulatifWeek, - "percentageActual" => $progressActualKomulatifWeek, + "percentageReal" => $progressActualKomulatifWeek, "data_details" => $dataActivityPlanDate ], From 6dc3ab828a798609e216d412911adb5c1b8c1afa Mon Sep 17 00:00:00 2001 From: ibnu Date: Sun, 3 Dec 2023 08:37:50 +0700 Subject: [PATCH 015/155] update for duration +1 --- app/Helpers/MasterFunctionsHelper.php | 177 +++++++++++++++++++++++++- 1 file changed, 176 insertions(+), 1 deletion(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index a507ec2..99196e7 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -565,6 +565,8 @@ class MasterFunctionsHelper # hitung untuk persentase progress planning if($keyPlanM->duration == 0){ $duration = 2; + }else{ + $duration = $keyPlanM->duration + 1; } // $startPlan = new DateTime($keyPlanM->planned_start); // $endPlan = new DateTime($keyPlanM->planned_end); @@ -950,7 +952,7 @@ class MasterFunctionsHelper return $dataFinal; } - public function calculateSCurve($projectId) + public function calculateSCurveOld($projectId) { DB::enableQueryLog(); @@ -1289,6 +1291,179 @@ class MasterFunctionsHelper return $dataFinal; } + public function calculateSCurve($projectId) + { + DB::enableQueryLog(); + + $dataFinal = []; + $dataPayload = []; + $dataPayload['period'] = 'week'; + $totalACWP = 0; + $totalBCWP = 0; + $tempPercentage = []; + + $dataProject = Project::find($projectId); + $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $projectId)->first(); + if (isset($dataPayload['end_date']) && $dataPayload['end_date'] > $dataProject->akhir_proyek) { + $dataPayload['end_date'] = $dataProject->akhir_proyek; + } + + if ($dataHeader) { + $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $projectId)->sum("rencana_biaya"); + } else { + $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $projectId)->sum("rencana_biaya"); + } + + $minDate = $dataProject->mulai_proyek; + + $begin = new \DateTime($minDate); + $begin = $begin->modify('-1 day'); + if (isset($dataPayload['end_date'])) { + $maxDate = $dataPayload['end_date']; + $end = new \DateTime($maxDate . ' Friday'); + // $end->modify('next Friday'); + // $end->modify('next Friday'); + /* $interval = \DateInterval::createFromDateString('1 day'); */// should be using this but its bugged + $interval = new \DateInterval('P1D'); + } else { + $maxDate = $dataProject->akhir_proyek; + $end = new \DateTime($maxDate); + $end = new \DateTime($maxDate->format('Y-m-d') . ' Friday'); + // $end->modify('next Friday'); + // $end->modify('next Friday'); + $interval = new \DateInterval('P1D'); + } + $period = new \DatePeriod($begin, $interval, $end); + + $arr_ActualM = []; + $tempDate = []; + $tempPercentagePlan = []; + $tempPercentagePlanWhr = []; + $tempPercentageReal = []; + $tempTtlPercentPlan = 0; + $tempTtlPercentActual = 0; + + $currentACWP = 0; + $currentBCWP = 0; + $dataActivityPlanDate = []; + $progressPlanKomulatifWeek = []; + $progressActualKomulatifWeek = []; + $dateWeek = []; + $tmpProgressPlanWeek = 0; + $tmpProgressActualWeek = 0; + foreach ($period as $dt) { + $loopDay = $dt->format("Y-m-d"); + //new \Datetime($dt->format("Y-m-d")); + // $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); + $tempDate[] = array($dt->format("Y-m-d")); + + $dataPlanM = DB::table('m_activity') + ->where('type_activity', 'task') + ->where('bobot_planning', '>', 0) + ->where('proyek_id', $projectId) + ->whereDate('planned_start', '<=', $loopDay) + ->whereDate('planned_end', '>=', $loopDay) + ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') + ->get(); + + $dataActualM = DB::table('report_activity_material as ram') + ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') + ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', + DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), + DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), + DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity') + ) + ->where('ram.report_date', $loopDay) + ->where('ma.proyek_id', $projectId) + ->get(); + + $dataActivityPlan = []; + $dataActivityActual = []; + $today = new DateTime(); + if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ + + $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); + if (new \DateTime($loopDay) < $today) { + // $tempPercentageReal[] = round($tempTtlPercentActual, 2); + $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); + } + $dateWeek[] = [$loopDay]; + } + // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; + foreach ($dataPlanM as $keyPlanM) { + # hitung untuk persentase progress planning + if($keyPlanM->duration == 0){ + $duration = 2; + } + // $startPlan = new DateTime($keyPlanM->planned_start); + // $endPlan = new DateTime($keyPlanM->planned_end); + // $interval = $startPlan->diff($endPlan); + + // // Mengambil hasil selisih hari + // $duration = $interval->days; + + $progressPlanWeek = $keyPlanM->bobot_planning / $duration; + $dataActivityPlan[] = array( + 'progressPlanDay' => $progressPlanWeek, + 'name' => $keyPlanM->name, + 'bobot_p' => $keyPlanM->bobot_planning, + 'duration' => $keyPlanM->duration + ); + $tmpProgressPlanWeek += $progressPlanWeek; + } + + // hitung progress actual + foreach ($dataActualM as $keyActualM) { + # hitung untuk persentase progress actual + // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; + if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; + }else{ + $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; + } + if($keyActualM->status_activity == 'done'){ + $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; + } + else{ + $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; + } + $dataActivityActual[] = array( + 'progressActualDay' => $progressActualWeek, + 'qty_act' => $keyActualM->qty_actual, + 'bobot_p' => $keyActualM->bobot_planning, + 'qty_plan' => $keyActualM->qty_plan, + 'status_activity' => $keyActualM->status_activity, + 'sum_qty_actual' => $keyActualM->sum_qty_actual, + 'name' => $keyActualM->name + ); + + $tmpProgressActualWeek += $progressActualWeek; + } + + $dataActivityPlanDate[] = array( + "date" => $loopDay, + "statusWeek" => new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday') ? true : false, + "activity-plan" => $dataActivityPlan, + "activity-actual" => $dataActivityActual, + "tmpProgressActualWeek" => $tmpProgressActualWeek, + "progressPlanWeek" => $tmpProgressPlanWeek + ); + + } + + $dataFinal[] = array( + // "date" => $dateWeek, + "proyek_name" => $dataProject->nama, + "data" => ["date" => $dateWeek, + "percentagePlan" => $progressPlanKomulatifWeek, + "percentageReal" => $progressActualKomulatifWeek, + "data_details" => $dataActivityPlanDate + ] + ); + + return $dataFinal; + } + public function calculateProgressBasedOnSimple($keyGantt) { DB::enableQueryLog(); From 0fa788e4f2cc306d1685a6e02a9ad0f86a8b17cc Mon Sep 17 00:00:00 2001 From: ibnu Date: Mon, 4 Dec 2023 03:35:39 +0700 Subject: [PATCH 016/155] update curva calculate add count_report --- app/Helpers/MasterFunctionsHelper.php | 117 ++++++++++++++++++++------ 1 file changed, 90 insertions(+), 27 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index 99196e7..fec14b8 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -542,7 +542,8 @@ class MasterFunctionsHelper ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), - DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity') + DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity'), + DB::raw('(SELECT COUNT(id) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS count_report') ) ->where('ram.report_date', $loopDay) ->where('ma.version_gantt_id', $keyGantt['id']) @@ -563,18 +564,25 @@ class MasterFunctionsHelper // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; foreach ($dataPlanM as $keyPlanM) { # hitung untuk persentase progress planning - if($keyPlanM->duration == 0){ - $duration = 2; - }else{ - $duration = $keyPlanM->duration + 1; - } + // if($keyPlanM->duration == 0){ + // $duration = 2; + // Tanggal awal + $startDate = new DateTime($keyPlanM->planned_start); + // Tanggal akhir + $endDate = new DateTime($keyPlanM->planned_end); + // Menghitung selisih hari + $interval = $startDate->diff($endDate); + // Mengambil hasil selisih hari + $duration = (int) $interval->days+1; + // }else{ + // $duration = $keyPlanM->duration + 2; + // } // $startPlan = new DateTime($keyPlanM->planned_start); // $endPlan = new DateTime($keyPlanM->planned_end); // $interval = $startPlan->diff($endPlan); // // Mengambil hasil selisih hari // $duration = $interval->days; - $progressPlanWeek = $keyPlanM->bobot_planning / $duration; $dataActivityPlan[] = array( 'progressPlanDay' => $progressPlanWeek, @@ -589,13 +597,36 @@ class MasterFunctionsHelper foreach ($dataActualM as $keyActualM) { # hitung untuk persentase progress actual // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; + // jika total report > dari planning if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; }else{ - $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; + // jika total report < dari planning + // $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; + if($keyActualM->qty_actual == 0){ + $progressActualWeek = 0; + }else{ + $progressActualWeek = ($keyActualM->qty_actual / $keyActualM->qty_plan) * $keyActualM->bobot_planning; + } } if($keyActualM->status_activity == 'done'){ - $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; + // if($keyActualM->count_report > 1){ + // $progressActualWeek = $keyActualM->bobot_planning/$keyActualM->count_report; + // }else{ + $progressActualWeek = $keyActualM->bobot_planning / $keyActualM->count_report; + // } + // if($progressActualWeek > $keyActualM->bobot_planning){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_actual == 0){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_plan == $keyActualM->sum_qty_actual){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else { + // $progressActualWeek = $progressActualWeek; + // } + // $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; + // jika report lebih dari 1 x, maka harusnya di bagi sabanyak jumlah report, + // contoh ada 3 report, report ke 1 adalah 5 maka 100/3 dan di looping } else{ $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; @@ -1328,23 +1359,23 @@ class MasterFunctionsHelper } else { $maxDate = $dataProject->akhir_proyek; $end = new \DateTime($maxDate); - $end = new \DateTime($maxDate->format('Y-m-d') . ' Friday'); + $end = new \DateTime($end->format('Y-m-d') . ' Friday'); // $end->modify('next Friday'); // $end->modify('next Friday'); $interval = new \DateInterval('P1D'); } $period = new \DatePeriod($begin, $interval, $end); - $arr_ActualM = []; + // $arr_ActualM = []; $tempDate = []; - $tempPercentagePlan = []; - $tempPercentagePlanWhr = []; - $tempPercentageReal = []; - $tempTtlPercentPlan = 0; - $tempTtlPercentActual = 0; + // $tempPercentagePlan = []; + // $tempPercentagePlanWhr = []; + // $tempPercentageReal = []; + // $tempTtlPercentPlan = 0; + // $tempTtlPercentActual = 0; - $currentACWP = 0; - $currentBCWP = 0; + // $currentACWP = 0; + // $currentBCWP = 0; $dataActivityPlanDate = []; $progressPlanKomulatifWeek = []; $progressActualKomulatifWeek = []; @@ -1371,7 +1402,8 @@ class MasterFunctionsHelper ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), - DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity') + DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity'), + DB::raw('(SELECT COUNT(id) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS count_report') ) ->where('ram.report_date', $loopDay) ->where('ma.proyek_id', $projectId) @@ -1392,16 +1424,26 @@ class MasterFunctionsHelper // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; foreach ($dataPlanM as $keyPlanM) { # hitung untuk persentase progress planning - if($keyPlanM->duration == 0){ - $duration = 2; - } + // if($keyPlanM->duration == 0){ + // $duration = 2; + // Tanggal awal + $startDate = new DateTime($keyPlanM->planned_start); + // Tanggal akhir + $endDate = new DateTime($keyPlanM->planned_end); + // Menghitung selisih hari + $interval = $startDate->diff($endDate); + // Mengambil hasil selisih hari + $duration = (int) $interval->days+1; + // }else{ + // $duration = $keyPlanM->duration + 2; + // } // $startPlan = new DateTime($keyPlanM->planned_start); // $endPlan = new DateTime($keyPlanM->planned_end); // $interval = $startPlan->diff($endPlan); // // Mengambil hasil selisih hari // $duration = $interval->days; - + // 2023-07-26 $progressPlanWeek = $keyPlanM->bobot_planning / $duration; $dataActivityPlan[] = array( 'progressPlanDay' => $progressPlanWeek, @@ -1416,13 +1458,34 @@ class MasterFunctionsHelper foreach ($dataActualM as $keyActualM) { # hitung untuk persentase progress actual // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; + // jika total report > dari planning if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; }else{ - $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; + // jika total report < dari planning + // $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; + if($keyActualM->qty_actual == 0){ + $progressActualWeek = 0; + }else{ + $progressActualWeek = ($keyActualM->qty_actual / $keyActualM->qty_plan) * $keyActualM->bobot_planning; + } } if($keyActualM->status_activity == 'done'){ - $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; + // if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + + // } + // if($progressActualWeek > $keyActualM->bobot_planning){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_actual == 0){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_plan == $keyActualM->sum_qty_actual){ + $progressActualWeek = $keyActualM->bobot_planning / $keyActualM->count_report; + // }else { + // $progressActualWeek = $progressActualWeek; + // } + // $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; + // jika report lebih dari 1 x, maka harusnya di bagi sabanyak jumlah report, + // contoh ada 3 report, report ke 1 adalah 5 maka 100/3 dan di looping } else{ $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; @@ -1456,8 +1519,8 @@ class MasterFunctionsHelper "proyek_name" => $dataProject->nama, "data" => ["date" => $dateWeek, "percentagePlan" => $progressPlanKomulatifWeek, - "percentageReal" => $progressActualKomulatifWeek, - "data_details" => $dataActivityPlanDate + "percentageReal" => $progressActualKomulatifWeek + // "data_details" => $dataActivityPlanDate ] ); From 16e73335bb60e60f0d5d5bf30868e77a0624ff16 Mon Sep 17 00:00:00 2001 From: ibnu Date: Mon, 4 Dec 2023 09:29:07 +0700 Subject: [PATCH 017/155] update for calculate progress --- .../Commands/CalculateProgressGantt.php | 29 +++++++++ app/Helpers/MasterFunctionsHelper.php | 20 +----- app/Http/Controllers/ActivityController.php | 5 ++ .../Controllers/HierarchyFtthController.php | 65 ++++++++++--------- 4 files changed, 72 insertions(+), 47 deletions(-) create mode 100644 app/Console/Commands/CalculateProgressGantt.php diff --git a/app/Console/Commands/CalculateProgressGantt.php b/app/Console/Commands/CalculateProgressGantt.php new file mode 100644 index 0000000..8e6796f --- /dev/null +++ b/app/Console/Commands/CalculateProgressGantt.php @@ -0,0 +1,29 @@ +argument('project_id'); + $project = Project::find($project_id); + + $project->calculation_status = true; + $project->save(); + + $data = MasterFunctionsHelper::CalculateSCurve($project_id); + + $project->scurve = json_encode($data); + $project->calculation_status = true; + $project->save(); + } +} diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index fec14b8..2f1770e 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -609,24 +609,8 @@ class MasterFunctionsHelper $progressActualWeek = ($keyActualM->qty_actual / $keyActualM->qty_plan) * $keyActualM->bobot_planning; } } - if($keyActualM->status_activity == 'done'){ - // if($keyActualM->count_report > 1){ - // $progressActualWeek = $keyActualM->bobot_planning/$keyActualM->count_report; - // }else{ - $progressActualWeek = $keyActualM->bobot_planning / $keyActualM->count_report; - // } - // if($progressActualWeek > $keyActualM->bobot_planning){ - // $progressActualWeek = $keyActualM->bobot_planning; - // }else if($keyActualM->qty_actual == 0){ - // $progressActualWeek = $keyActualM->bobot_planning; - // }else if($keyActualM->qty_plan == $keyActualM->sum_qty_actual){ - // $progressActualWeek = $keyActualM->bobot_planning; - // }else { - // $progressActualWeek = $progressActualWeek; - // } - // $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; - // jika report lebih dari 1 x, maka harusnya di bagi sabanyak jumlah report, - // contoh ada 3 report, report ke 1 adalah 5 maka 100/3 dan di looping + if($keyActualM->status_activity == 'done'){ + $progressActualWeek = $keyActualM->bobot_planning / $keyActualM->count_report; } else{ $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index c2a8223..610c5fc 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -1156,4 +1156,9 @@ class ActivityController extends Controller } return response()->json(['status' => 'success', 'data' => $request, 'message' => 'Update successful!', 'code' => 200], 200); } + + // public function recalculateProject($by, $id){ + // // query get activity + // $cekActivity = + // } } diff --git a/app/Http/Controllers/HierarchyFtthController.php b/app/Http/Controllers/HierarchyFtthController.php index 3b3f64f..a31c626 100644 --- a/app/Http/Controllers/HierarchyFtthController.php +++ b/app/Http/Controllers/HierarchyFtthController.php @@ -6,6 +6,7 @@ use Illuminate\Http\Request; use App\Models\HierarchyFtth; use App\Models\VersionGantt; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Artisan; class HierarchyFtthController extends Controller { @@ -103,35 +104,40 @@ class HierarchyFtthController extends Controller } public function countProgress($project_id) { - $ftthIds = VersionGantt::select('hierarchy_ftth_id') - ->where('proyek_id', $project_id) - ->groupBy('hierarchy_ftth_id') - ->get(); - if($ftthIds){ - foreach ($ftthIds as $ftthId) { - $gantts = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->sum('progress'); - $bobot_planning = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->sum('bobot'); - $ganttCount = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->count(); - - $ftth = HierarchyFtth::find($ftthId->hierarchy_ftth_id); - if($ftth){ - $round = $gantts/$ganttCount; - $round_bobot = $bobot_planning/$ganttCount; - $ftth->progress = round($round, 2); - $ftth->bobot_planning = round($round_bobot, 2); - try { - $ftth->save(); - } catch (\Exception $e) { - // Log the error or handle it in some other way - Log::error($e->getMessage()); - } - - if($ftth->parent_id){ - $this->countParent($ftth); - } - } - } - } + // $ftthIds = VersionGantt::select('hierarchy_ftth_id') + // ->where('proyek_id', $project_id) + // ->groupBy('hierarchy_ftth_id') + // ->get(); + // if($ftthIds){ + // foreach ($ftthIds as $ftthId) { + // $gantts = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->sum('progress'); + // $bobot_planning = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->sum('bobot'); + // $ganttCount = VersionGantt::where('hierarchy_ftth_id', $ftthId->hierarchy_ftth_id)->count(); + + // $ftth = HierarchyFtth::find($ftthId->hierarchy_ftth_id); + // if($ftth){ + // $round = $gantts/$ganttCount; + // $round_bobot = $bobot_planning/$ganttCount; + // $ftth->progress = round($round, 2); + // $ftth->bobot_planning = round($round_bobot, 2); + // try { + // $ftth->save(); + // } catch (\Exception $e) { + // // Log the error or handle it in some other way + // Log::error($e->getMessage()); + // } + + // if($ftth->parent_id){ + // $this->countParent($ftth); + // } + // } + // } + // } + + // calculate ke curva berdasarkan site + Artisan::call('calculate:progressgantt', [ + 'project_id' => $project_id + ]); } public function countParent($ftth){ @@ -180,6 +186,7 @@ class HierarchyFtthController extends Controller public function getTreeByProject($project_id) { $this->countProgress(intval($project_id)); + $data = HierarchyFtth::where('project_id', $project_id)->whereNull('parent_id')->orderByRaw('id ASC')->get(); $finalData = []; foreach($data as $objRow){ From 2703a32aeb60cfbf1e3bbdaf5906e141a9f53b30 Mon Sep 17 00:00:00 2001 From: wahyu Date: Mon, 4 Dec 2023 11:50:23 +0700 Subject: [PATCH 018/155] calculate s curve by hierarchy id --- .../Commands/CalculateProgressGantt.php | 10 ++- app/Console/Kernel.php | 3 +- app/Helpers/MasterFunctionsHelper.php | 88 ++++++++++++++----- app/Http/Controllers/ActivityController.php | 2 +- .../Controllers/HierarchyFtthController.php | 7 +- 5 files changed, 76 insertions(+), 34 deletions(-) diff --git a/app/Console/Commands/CalculateProgressGantt.php b/app/Console/Commands/CalculateProgressGantt.php index 8e6796f..6db1d41 100644 --- a/app/Console/Commands/CalculateProgressGantt.php +++ b/app/Console/Commands/CalculateProgressGantt.php @@ -2,25 +2,27 @@ namespace App\Console\Commands; +use App\Models\HierarchyFtth; use Illuminate\Console\Command; use App\Helpers\MasterFunctionsHelper; use App\Models\Project; class CalculateProgressGantt extends Command { - protected $signature = 'calculate:progressgantt {project_id}'; + protected $signature = 'calculate:progressgantt {hierarchy_id}'; protected $description = 'Calculate Progress Gantt'; public function handle() { - $project_id = $this->argument('project_id'); - $project = Project::find($project_id); + $hierarchy_id = $this->argument('hierarchy_id'); + $hierarchy = HierarchyFtth::findOrFail($hierarchy_id); + $project = Project::find($hierarchy->project_id); $project->calculation_status = true; $project->save(); - $data = MasterFunctionsHelper::CalculateSCurve($project_id); + $data = MasterFunctionsHelper::CalculateSCurve(null, $hierarchy_id); $project->scurve = json_encode($data); $project->calculation_status = true; diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index a7fceee..726d069 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -14,7 +14,8 @@ class Kernel extends ConsoleKernel */ protected $commands = [ Commands\syncHumanResourceIntegration::class, - Commands\CalculateSCurve::class + Commands\CalculateSCurve::class, + Commands\CalculateProgressGantt::class ]; /** diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index 2f1770e..dfc4d89 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -1306,10 +1306,19 @@ class MasterFunctionsHelper return $dataFinal; } - public function calculateSCurve($projectId) + public function calculateSCurve($projectId, $hierarchyId = null) { DB::enableQueryLog(); + $hierarchyGantts = []; + if (isset($hierarchyId)) { + $hierarchy = HierarchyFtth::findOrFail($hierarchyId); + $projectId = $hierarchy->project_id; + if (isset($hierarchy)) { + $hierarchyGantts = VersionGantt::where('hierarchy_ftth_id', $hierarchyId)->get()->toArray(); + } + } + $dataFinal = []; $dataPayload = []; $dataPayload['period'] = 'week'; @@ -1371,17 +1380,43 @@ class MasterFunctionsHelper //new \Datetime($dt->format("Y-m-d")); // $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); $tempDate[] = array($dt->format("Y-m-d")); + $dataPlanM = []; + $dataActualM = []; + if (count($hierarchyGantts) > 0) { + foreach ($hierarchyGantts as $key => $gantt) { + $dataPlanM[] = DB::table('m_activity') + ->where('type_activity', 'task') + ->where('bobot_planning', '>', 0) + ->where('version_gantt_id', $gantt['id']) + ->whereDate('planned_start', '<=', $loopDay) + ->whereDate('planned_end', '>=', $loopDay) + ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') + ->get()->toArray(); + + $dataActualM[] = DB::table('report_activity_material as ram') + ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') + ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', + DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), + DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), + DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity'), + DB::raw('(SELECT COUNT(id) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS count_report') + ) + ->where('ram.report_date', $loopDay) + ->where('ma.version_gantt_id', $gantt['id']) + ->get()->toArray(); + } + } else { - $dataPlanM = DB::table('m_activity') + $dataPlanM[] = DB::table('m_activity') ->where('type_activity', 'task') ->where('bobot_planning', '>', 0) ->where('proyek_id', $projectId) ->whereDate('planned_start', '<=', $loopDay) ->whereDate('planned_end', '>=', $loopDay) ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') - ->get(); + ->get()->toArray(); - $dataActualM = DB::table('report_activity_material as ram') + $dataActualM[] = DB::table('report_activity_material as ram') ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), @@ -1391,7 +1426,8 @@ class MasterFunctionsHelper ) ->where('ram.report_date', $loopDay) ->where('ma.proyek_id', $projectId) - ->get(); + ->get()->toArray(); + } $dataActivityPlan = []; $dataActivityActual = []; @@ -1406,14 +1442,15 @@ class MasterFunctionsHelper $dateWeek[] = [$loopDay]; } // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; + if (count($dataPlanM) > 0 && count($dataPlanM[0]) > 0) { foreach ($dataPlanM as $keyPlanM) { # hitung untuk persentase progress planning // if($keyPlanM->duration == 0){ // $duration = 2; // Tanggal awal - $startDate = new DateTime($keyPlanM->planned_start); + $startDate = new DateTime($keyPlanM[0]->planned_start); // Tanggal akhir - $endDate = new DateTime($keyPlanM->planned_end); + $endDate = new DateTime($keyPlanM[0]->planned_end); // Menghitung selisih hari $interval = $startDate->diff($endDate); // Mengambil hasil selisih hari @@ -1428,33 +1465,35 @@ class MasterFunctionsHelper // // Mengambil hasil selisih hari // $duration = $interval->days; // 2023-07-26 - $progressPlanWeek = $keyPlanM->bobot_planning / $duration; + $progressPlanWeek = $keyPlanM[0]->bobot_planning / $duration; $dataActivityPlan[] = array( 'progressPlanDay' => $progressPlanWeek, - 'name' => $keyPlanM->name, - 'bobot_p' => $keyPlanM->bobot_planning, - 'duration' => $keyPlanM->duration + 'name' => $keyPlanM[0]->name, + 'bobot_p' => $keyPlanM[0]->bobot_planning, + 'duration' => $keyPlanM[0]->duration ); $tmpProgressPlanWeek += $progressPlanWeek; } + } // hitung progress actual + if (count($dataActualM) > 0 && count($dataActualM[0]) > 0) { foreach ($dataActualM as $keyActualM) { # hitung untuk persentase progress actual // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; // jika total report > dari planning - if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ - $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; + if($keyActualM[0]->sum_qty_actual > $keyActualM[0]->qty_plan){ + $progressActualWeek = (($keyActualM[0]->qty_actual / $keyActualM[0]->sum_qty_actual) * 100) *$keyActualM[0]->bobot_planning/100; }else{ // jika total report < dari planning // $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; - if($keyActualM->qty_actual == 0){ + if($keyActualM[0]->qty_actual == 0){ $progressActualWeek = 0; }else{ - $progressActualWeek = ($keyActualM->qty_actual / $keyActualM->qty_plan) * $keyActualM->bobot_planning; + $progressActualWeek = ($keyActualM[0]->qty_actual / $keyActualM[0]->qty_plan) * $keyActualM[0]->bobot_planning; } } - if($keyActualM->status_activity == 'done'){ + if($keyActualM[0]->status_activity == 'done'){ // if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ // } @@ -1463,7 +1502,7 @@ class MasterFunctionsHelper // }else if($keyActualM->qty_actual == 0){ // $progressActualWeek = $keyActualM->bobot_planning; // }else if($keyActualM->qty_plan == $keyActualM->sum_qty_actual){ - $progressActualWeek = $keyActualM->bobot_planning / $keyActualM->count_report; + $progressActualWeek = $keyActualM[0]->bobot_planning / $keyActualM[0]->count_report; // }else { // $progressActualWeek = $progressActualWeek; // } @@ -1472,20 +1511,21 @@ class MasterFunctionsHelper // contoh ada 3 report, report ke 1 adalah 5 maka 100/3 dan di looping } else{ - $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; + $progressActualWeek = $progressActualWeek > ($keyActualM[0]->bobot_planning*95)/100 ? ($keyActualM[0]->bobot_planning*95)/100 : $progressActualWeek; } $dataActivityActual[] = array( 'progressActualDay' => $progressActualWeek, - 'qty_act' => $keyActualM->qty_actual, - 'bobot_p' => $keyActualM->bobot_planning, - 'qty_plan' => $keyActualM->qty_plan, - 'status_activity' => $keyActualM->status_activity, - 'sum_qty_actual' => $keyActualM->sum_qty_actual, - 'name' => $keyActualM->name + 'qty_act' => $keyActualM[0]->qty_actual, + 'bobot_p' => $keyActualM[0]->bobot_planning, + 'qty_plan' => $keyActualM[0]->qty_plan, + 'status_activity' => $keyActualM[0]->status_activity, + 'sum_qty_actual' => $keyActualM[0]->sum_qty_actual, + 'name' => $keyActualM[0]->name ); $tmpProgressActualWeek += $progressActualWeek; } + } $dataActivityPlanDate[] = array( "date" => $loopDay, diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index 610c5fc..cbb425e 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -322,7 +322,7 @@ class ActivityController extends Controller $actualEndValues = array_column(array_filter($dataFinal, function($item) { return isset($item['actual_end']); }), 'actual_end'); - $returnActualStartOrEnd = count($actualEndValues) == count($dataFinal) ? max($actualEndValues) : null; + $returnActualStartOrEnd = count($actualEndValues) == count($dataFinal) && count($actualEndValues) > 0 ? max($actualEndValues) : null; if (isset($parent)) { $parent->actual_end = $returnActualStartOrEnd; $parent->save(); diff --git a/app/Http/Controllers/HierarchyFtthController.php b/app/Http/Controllers/HierarchyFtthController.php index a31c626..c880d6e 100644 --- a/app/Http/Controllers/HierarchyFtthController.php +++ b/app/Http/Controllers/HierarchyFtthController.php @@ -103,7 +103,7 @@ class HierarchyFtthController extends Controller } } - public function countProgress($project_id) { + public function countProgress($hierarchy_id) { // $ftthIds = VersionGantt::select('hierarchy_ftth_id') // ->where('proyek_id', $project_id) // ->groupBy('hierarchy_ftth_id') @@ -136,7 +136,7 @@ class HierarchyFtthController extends Controller // calculate ke curva berdasarkan site Artisan::call('calculate:progressgantt', [ - 'project_id' => $project_id + 'hierarchy_id' => $hierarchy_id ]); } @@ -185,12 +185,11 @@ class HierarchyFtthController extends Controller public function getTreeByProject($project_id) { - $this->countProgress(intval($project_id)); - $data = HierarchyFtth::where('project_id', $project_id)->whereNull('parent_id')->orderByRaw('id ASC')->get(); $finalData = []; foreach($data as $objRow){ $objRow->key = rand(1, 1000); + $this->countProgress(intval($objRow->id)); if (VersionGantt::where('hierarchy_ftth_id', $objRow->id)->exists()) { $dataGantt = VersionGantt::where('hierarchy_ftth_id', $objRow->id)->get(); $progress = $this->ganttProgress('hierarchy_ftth_id', $objRow->id); From acb7a56a3cfba80e488b4ec5437e585d739a44c8 Mon Sep 17 00:00:00 2001 From: wahyu Date: Mon, 4 Dec 2023 14:22:15 +0700 Subject: [PATCH 019/155] update count hierarchy --- app/Console/Commands/CalculateProgressGantt.php | 9 +++------ app/Http/Controllers/HierarchyFtthController.php | 9 +++++++-- routes/web.php | 1 + 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/app/Console/Commands/CalculateProgressGantt.php b/app/Console/Commands/CalculateProgressGantt.php index 6db1d41..3e9f81c 100644 --- a/app/Console/Commands/CalculateProgressGantt.php +++ b/app/Console/Commands/CalculateProgressGantt.php @@ -19,13 +19,10 @@ class CalculateProgressGantt extends Command $hierarchy = HierarchyFtth::findOrFail($hierarchy_id); $project = Project::find($hierarchy->project_id); - $project->calculation_status = true; - $project->save(); - $data = MasterFunctionsHelper::CalculateSCurve(null, $hierarchy_id); - $project->scurve = json_encode($data); - $project->calculation_status = true; - $project->save(); + $hierarchy->bobot_planning = end($data[0]['data']['percentagePlan']); + $hierarchy->progress = end($data[0]['data']['percentageReal']); + $hierarchy->save(); } } diff --git a/app/Http/Controllers/HierarchyFtthController.php b/app/Http/Controllers/HierarchyFtthController.php index c880d6e..bcf27ad 100644 --- a/app/Http/Controllers/HierarchyFtthController.php +++ b/app/Http/Controllers/HierarchyFtthController.php @@ -189,7 +189,6 @@ class HierarchyFtthController extends Controller $finalData = []; foreach($data as $objRow){ $objRow->key = rand(1, 1000); - $this->countProgress(intval($objRow->id)); if (VersionGantt::where('hierarchy_ftth_id', $objRow->id)->exists()) { $dataGantt = VersionGantt::where('hierarchy_ftth_id', $objRow->id)->get(); $progress = $this->ganttProgress('hierarchy_ftth_id', $objRow->id); @@ -210,7 +209,13 @@ class HierarchyFtthController extends Controller return response()->json(['status'=>'success','data'=>$finalData,'code'=>200], 200); } - + public function countProgressTree($hierarchy_id) + { + Artisan::call('calculate:progressgantt', [ + 'hierarchy_id' => $hierarchy_id + ]); + return response()->json(['status'=>'success','code'=>200], 200); + } private function getChildren($project_id, $parent_id) { $finalData = []; diff --git a/routes/web.php b/routes/web.php index 14e1d08..f82f295 100644 --- a/routes/web.php +++ b/routes/web.php @@ -491,6 +491,7 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->put('/hierarchy-ftths/{id}', 'HierarchyFtthController@update'); $router->delete('/hierarchy-ftths/{id}', 'HierarchyFtthController@destroy'); $router->get('/hierarchy-ftths/tree/{project_id}', 'HierarchyFtthController@getTreeByProject'); + $router->get('/hierarchy-ftths/count-tree/{hierarchy_id}', 'HierarchyFtthController@countProgressTree'); $router->get('/hierarchy-ftths/tree-gantt/{gantt_id}', 'HierarchyFtthController@getTreeByGantt'); $router->post('/map-monitoring/search', 'MapMonitoringController@search'); From fb308af91bb7ec19652c97665ec2b8554df06b76 Mon Sep 17 00:00:00 2001 From: ibnu Date: Mon, 4 Dec 2023 15:57:52 +0700 Subject: [PATCH 020/155] update calculate progress hierarchy --- .../Commands/CalculateProgressGantt.php | 6 +- app/Helpers/MasterFunctionsHelper.php | 480 +++++++++++++----- 2 files changed, 368 insertions(+), 118 deletions(-) diff --git a/app/Console/Commands/CalculateProgressGantt.php b/app/Console/Commands/CalculateProgressGantt.php index 3e9f81c..5ac1e5f 100644 --- a/app/Console/Commands/CalculateProgressGantt.php +++ b/app/Console/Commands/CalculateProgressGantt.php @@ -19,10 +19,10 @@ class CalculateProgressGantt extends Command $hierarchy = HierarchyFtth::findOrFail($hierarchy_id); $project = Project::find($hierarchy->project_id); - $data = MasterFunctionsHelper::CalculateSCurve(null, $hierarchy_id); + $data = MasterFunctionsHelper::calculateSCurveForProgressTree($hierarchy_id); - $hierarchy->bobot_planning = end($data[0]['data']['percentagePlan']); - $hierarchy->progress = end($data[0]['data']['percentageReal']); + $hierarchy->bobot_planning = 100; + $hierarchy->progress =((int) end($data[0]['data']['percentageReal']) / (int) end($data[0]['data']['percentagePlan'])) * 100; $hierarchy->save(); } } diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index dfc4d89..acf3f69 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -1306,18 +1306,18 @@ class MasterFunctionsHelper return $dataFinal; } - public function calculateSCurve($projectId, $hierarchyId = null) + public function calculateSCurve($projectId) { DB::enableQueryLog(); - $hierarchyGantts = []; - if (isset($hierarchyId)) { - $hierarchy = HierarchyFtth::findOrFail($hierarchyId); - $projectId = $hierarchy->project_id; - if (isset($hierarchy)) { - $hierarchyGantts = VersionGantt::where('hierarchy_ftth_id', $hierarchyId)->get()->toArray(); - } - } + // $hierarchyGantts = []; + // if (isset($hierarchyId)) { + // $hierarchy = HierarchyFtth::findOrFail($hierarchyId); + // $projectId = $hierarchy->project_id; + // // if (isset($hierarchy)) { + // // $hierarchyGantts = VersionGantt::where('hierarchy_ftth_id', $hierarchyId)->get()->toArray(); + // // } + // } $dataFinal = []; $dataPayload = []; @@ -1333,9 +1333,9 @@ class MasterFunctionsHelper } if ($dataHeader) { - $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $projectId)->sum("rencana_biaya"); + // $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $projectId)->sum("rencana_biaya"); } else { - $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $projectId)->sum("rencana_biaya"); + // $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $projectId)->sum("rencana_biaya"); } $minDate = $dataProject->mulai_proyek; @@ -1382,41 +1382,41 @@ class MasterFunctionsHelper $tempDate[] = array($dt->format("Y-m-d")); $dataPlanM = []; $dataActualM = []; - if (count($hierarchyGantts) > 0) { - foreach ($hierarchyGantts as $key => $gantt) { - $dataPlanM[] = DB::table('m_activity') - ->where('type_activity', 'task') - ->where('bobot_planning', '>', 0) - ->where('version_gantt_id', $gantt['id']) - ->whereDate('planned_start', '<=', $loopDay) - ->whereDate('planned_end', '>=', $loopDay) - ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') - ->get()->toArray(); - - $dataActualM[] = DB::table('report_activity_material as ram') - ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') - ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', - DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), - DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), - DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity'), - DB::raw('(SELECT COUNT(id) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS count_report') - ) - ->where('ram.report_date', $loopDay) - ->where('ma.version_gantt_id', $gantt['id']) - ->get()->toArray(); - } - } else { + // if (count($hierarchyGantts) > 0) { + // foreach ($hierarchyGantts as $key => $gantt) { + // $dataPlanM[] = DB::table('m_activity') + // ->where('type_activity', 'task') + // ->where('bobot_planning', '>', 0) + // ->where('version_gantt_id', $gantt['id']) + // ->whereDate('planned_start', '<=', $loopDay) + // ->whereDate('planned_end', '>=', $loopDay) + // ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') + // ->get()->toArray(); + + // $dataActualM[] = DB::table('report_activity_material as ram') + // ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') + // ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', + // DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), + // DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), + // DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity'), + // DB::raw('(SELECT COUNT(id) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS count_report') + // ) + // ->where('ram.report_date', $loopDay) + // ->where('ma.version_gantt_id', $gantt['id']) + // ->get()->toArray(); + // } + // } else { - $dataPlanM[] = DB::table('m_activity') + $dataPlanM = DB::table('m_activity') ->where('type_activity', 'task') ->where('bobot_planning', '>', 0) ->where('proyek_id', $projectId) ->whereDate('planned_start', '<=', $loopDay) ->whereDate('planned_end', '>=', $loopDay) ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') - ->get()->toArray(); + ->get(); - $dataActualM[] = DB::table('report_activity_material as ram') + $dataActualM = DB::table('report_activity_material as ram') ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), @@ -1426,8 +1426,8 @@ class MasterFunctionsHelper ) ->where('ram.report_date', $loopDay) ->where('ma.proyek_id', $projectId) - ->get()->toArray(); - } + ->get(); + // } $dataActivityPlan = []; $dataActivityActual = []; @@ -1442,90 +1442,340 @@ class MasterFunctionsHelper $dateWeek[] = [$loopDay]; } // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; - if (count($dataPlanM) > 0 && count($dataPlanM[0]) > 0) { - foreach ($dataPlanM as $keyPlanM) { - # hitung untuk persentase progress planning - // if($keyPlanM->duration == 0){ - // $duration = 2; - // Tanggal awal - $startDate = new DateTime($keyPlanM[0]->planned_start); - // Tanggal akhir - $endDate = new DateTime($keyPlanM[0]->planned_end); - // Menghitung selisih hari - $interval = $startDate->diff($endDate); - // Mengambil hasil selisih hari - $duration = (int) $interval->days+1; - // }else{ - // $duration = $keyPlanM->duration + 2; - // } - // $startPlan = new DateTime($keyPlanM->planned_start); - // $endPlan = new DateTime($keyPlanM->planned_end); - // $interval = $startPlan->diff($endPlan); - - // // Mengambil hasil selisih hari - // $duration = $interval->days; - // 2023-07-26 - $progressPlanWeek = $keyPlanM[0]->bobot_planning / $duration; - $dataActivityPlan[] = array( - 'progressPlanDay' => $progressPlanWeek, - 'name' => $keyPlanM[0]->name, - 'bobot_p' => $keyPlanM[0]->bobot_planning, - 'duration' => $keyPlanM[0]->duration - ); - $tmpProgressPlanWeek += $progressPlanWeek; - } - } + // if (count($dataPlanM) > 0 && count($dataPlanM[0]) > 0) { + foreach ($dataPlanM as $keyPlanM) { + # hitung untuk persentase progress planning + // if($keyPlanM->duration == 0){ + // $duration = 2; + // Tanggal awal + $startDate = new DateTime($keyPlanM->planned_start); + // Tanggal akhir + $endDate = new DateTime($keyPlanM->planned_end); + // Menghitung selisih hari + $interval = $startDate->diff($endDate); + // Mengambil hasil selisih hari + $duration = (int) $interval->days+1; + // }else{ + // $duration = $keyPlanM->duration + 2; + // } + // $startPlan = new DateTime($keyPlanM->planned_start); + // $endPlan = new DateTime($keyPlanM->planned_end); + // $interval = $startPlan->diff($endPlan); + + // // Mengambil hasil selisih hari + // $duration = $interval->days; + // 2023-07-26 + $progressPlanWeek = $keyPlanM->bobot_planning / $duration; + $dataActivityPlan[] = array( + 'progressPlanDay' => $progressPlanWeek, + 'name' => $keyPlanM->name, + 'bobot_p' => $keyPlanM->bobot_planning, + 'duration' => $keyPlanM->duration + ); + $tmpProgressPlanWeek += $progressPlanWeek; + } + // } // hitung progress actual - if (count($dataActualM) > 0 && count($dataActualM[0]) > 0) { - foreach ($dataActualM as $keyActualM) { - # hitung untuk persentase progress actual - // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; - // jika total report > dari planning - if($keyActualM[0]->sum_qty_actual > $keyActualM[0]->qty_plan){ - $progressActualWeek = (($keyActualM[0]->qty_actual / $keyActualM[0]->sum_qty_actual) * 100) *$keyActualM[0]->bobot_planning/100; - }else{ - // jika total report < dari planning - // $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; - if($keyActualM[0]->qty_actual == 0){ - $progressActualWeek = 0; + // if (count($dataActualM) > 0 && count($dataActualM[0]) > 0) { + foreach ($dataActualM as $keyActualM) { + # hitung untuk persentase progress actual + // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; + // jika total report > dari planning + if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; }else{ - $progressActualWeek = ($keyActualM[0]->qty_actual / $keyActualM[0]->qty_plan) * $keyActualM[0]->bobot_planning; + // jika total report < dari planning + // $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; + if($keyActualM->qty_actual == 0){ + $progressActualWeek = 0; + }else{ + $progressActualWeek = ($keyActualM->qty_actual / $keyActualM->qty_plan) * $keyActualM->bobot_planning; + } + } + if($keyActualM->status_activity == 'done'){ + // if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + + // } + // if($progressActualWeek > $keyActualM->bobot_planning){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_actual == 0){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_plan == $keyActualM->sum_qty_actual){ + $progressActualWeek = $keyActualM->bobot_planning / $keyActualM->count_report; + // }else { + // $progressActualWeek = $progressActualWeek; + // } + // $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; + // jika report lebih dari 1 x, maka harusnya di bagi sabanyak jumlah report, + // contoh ada 3 report, report ke 1 adalah 5 maka 100/3 dan di looping } + else{ + $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; + } + $dataActivityActual[] = array( + 'progressActualDay' => $progressActualWeek, + 'qty_act' => $keyActualM->qty_actual, + 'bobot_p' => $keyActualM->bobot_planning, + 'qty_plan' => $keyActualM->qty_plan, + 'status_activity' => $keyActualM->status_activity, + 'sum_qty_actual' => $keyActualM->sum_qty_actual, + 'name' => $keyActualM->name + ); + + $tmpProgressActualWeek += $progressActualWeek; } - if($keyActualM[0]->status_activity == 'done'){ - // if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + // } + $dataActivityPlanDate[] = array( + "date" => $loopDay, + "statusWeek" => new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday') ? true : false, + "activity-plan" => $dataActivityPlan, + "activity-actual" => $dataActivityActual, + "tmpProgressActualWeek" => $tmpProgressActualWeek, + "progressPlanWeek" => $tmpProgressPlanWeek + ); + + } + + $dataFinal[] = array( + // "date" => $dateWeek, + "proyek_name" => $dataProject->nama, + "data" => ["date" => $dateWeek, + "percentagePlan" => $progressPlanKomulatifWeek, + "percentageReal" => $progressActualKomulatifWeek + // "data_details" => $dataActivityPlanDate + ] + ); + + return $dataFinal; + } + + public function calculateSCurveForProgressTree($hierarchyId) + { + DB::enableQueryLog(); + + // $hierarchyGantts = []; + if (isset($hierarchyId)) { + $hierarchy = HierarchyFtth::findOrFail($hierarchyId); + $projectId = $hierarchy->project_id; + // if (isset($hierarchy)) { + // $hierarchyGantts = VersionGantt::where('hierarchy_ftth_id', $hierarchyId)->get()->toArray(); + // } + } + + $dataFinal = []; + $dataPayload = []; + $dataPayload['period'] = 'week'; + $totalACWP = 0; + $totalBCWP = 0; + $tempPercentage = []; + + $dataProject = Project::find($projectId); + $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $projectId)->first(); + if (isset($dataPayload['end_date']) && $dataPayload['end_date'] > $dataProject->akhir_proyek) { + $dataPayload['end_date'] = $dataProject->akhir_proyek; + } + + if ($dataHeader) { + // $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $projectId)->sum("rencana_biaya"); + } else { + // $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $projectId)->sum("rencana_biaya"); + } + + $minDate = $dataProject->mulai_proyek; + + $begin = new \DateTime($minDate); + $begin = $begin->modify('-1 day'); + if (isset($dataPayload['end_date'])) { + $maxDate = $dataPayload['end_date']; + $end = new \DateTime($maxDate . ' Friday'); + // $end->modify('next Friday'); + // $end->modify('next Friday'); + /* $interval = \DateInterval::createFromDateString('1 day'); */// should be using this but its bugged + $interval = new \DateInterval('P1D'); + } else { + $maxDate = $dataProject->akhir_proyek; + $end = new \DateTime($maxDate); + $end = new \DateTime($end->format('Y-m-d') . ' Friday'); + // $end->modify('next Friday'); + // $end->modify('next Friday'); + $interval = new \DateInterval('P1D'); + } + $period = new \DatePeriod($begin, $interval, $end); + + // $arr_ActualM = []; + $tempDate = []; + // $tempPercentagePlan = []; + // $tempPercentagePlanWhr = []; + // $tempPercentageReal = []; + // $tempTtlPercentPlan = 0; + // $tempTtlPercentActual = 0; + + // $currentACWP = 0; + // $currentBCWP = 0; + $dataActivityPlanDate = []; + $progressPlanKomulatifWeek = []; + $progressActualKomulatifWeek = []; + $dateWeek = []; + $tmpProgressPlanWeek = 0; + $tmpProgressActualWeek = 0; + foreach ($period as $dt) { + $loopDay = $dt->format("Y-m-d"); + //new \Datetime($dt->format("Y-m-d")); + // $minSevenDays = $minSevenDays->modify('-7 day')->format("Y-m-d"); + $tempDate[] = array($dt->format("Y-m-d")); + $dataPlanM = []; + $dataActualM = []; + // if (count($hierarchyGantts) > 0) { + // foreach ($hierarchyGantts as $key => $gantt) { + // $dataPlanM[] = DB::table('m_activity') + // ->where('type_activity', 'task') + // ->where('bobot_planning', '>', 0) + // ->where('version_gantt_id', $gantt['id']) + // ->whereDate('planned_start', '<=', $loopDay) + // ->whereDate('planned_end', '>=', $loopDay) + // ->select('name', 'bobot_planning', 'biaya_actual', 'duration', 'persentase_progress', 'id', 'planned_start', 'planned_end') + // ->get()->toArray(); + + // $dataActualM[] = DB::table('report_activity_material as ram') + // ->join('m_activity as ma', 'ma.id', '=', 'ram.activity_id') + // ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', + // DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), + // DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), + // DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity'), + // DB::raw('(SELECT COUNT(id) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS count_report') + // ) + // ->where('ram.report_date', $loopDay) + // ->where('ma.version_gantt_id', $gantt['id']) + // ->get()->toArray(); + // } + // } else { + + $dataPlanM = DB::table('m_hierarchy_ftth as mhf') + ->join('m_version_gantt as mvg', 'mvg.hierarchy_ftth_id', '=', 'mhf.id') + ->join('m_activity as ma', 'ma.version_gantt_id', '=', 'mvg.id') + ->where('ma.type_activity', 'task') + ->where('ma.bobot_planning', '>', 0) + ->where('mhf.project_id', $projectId) + ->whereDate('planned_start', '<=', $loopDay) + ->whereDate('planned_end', '>=', $loopDay) + ->select('ma.name', 'ma.bobot_planning', 'ma.biaya_actual', 'ma.duration', 'ma.persentase_progress', 'ma.id', 'ma.planned_start', 'ma.planned_end') + ->get(); + + $dataActualM = DB::table('m_hierarchy_ftth as mhf') + ->join('m_version_gantt as mvg', 'mvg.hierarchy_ftth_id', '=', 'mhf.id') + ->join('m_activity as ma', 'ma.version_gantt_id', '=', 'mvg.id') + ->join('report_activity_material as ram', 'ram.activity_id', '=', 'ma.id') + ->select('ram.activity_id', 'ram.qty as qty_actual', 'ma.bobot_planning', 'ma.name', + DB::raw('(SELECT SUM(amta.qty_planning) FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS qty_plan'), + DB::raw('(SELECT SUM(ram.qty) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS sum_qty_actual'), + DB::raw('(SELECT DISTINCT status_activity FROM assign_material_to_activity amta WHERE amta.activity_id = ram.activity_id) AS status_activity'), + DB::raw('(SELECT COUNT(id) FROM report_activity_material ram WHERE ram.activity_id = ma.id) AS count_report') + ) + ->where('ram.report_date', $loopDay) + // ->where('ma.proyek_id', $projectId) + ->where('mhf.project_id', $projectId) + ->get(); + // } + + $dataActivityPlan = []; + $dataActivityActual = []; + $today = new DateTime(); + if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ + + $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); + if (new \DateTime($loopDay) < $today) { + // $tempPercentageReal[] = round($tempTtlPercentActual, 2); + $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); + } + $dateWeek[] = [$loopDay]; + } + // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; + // if (count($dataPlanM) > 0 && count($dataPlanM[0]) > 0) { + foreach ($dataPlanM as $keyPlanM) { + # hitung untuk persentase progress planning + // if($keyPlanM->duration == 0){ + // $duration = 2; + // Tanggal awal + $startDate = new DateTime($keyPlanM->planned_start); + // Tanggal akhir + $endDate = new DateTime($keyPlanM->planned_end); + // Menghitung selisih hari + $interval = $startDate->diff($endDate); + // Mengambil hasil selisih hari + $duration = (int) $interval->days+1; + // }else{ + // $duration = $keyPlanM->duration + 2; // } - // if($progressActualWeek > $keyActualM->bobot_planning){ - // $progressActualWeek = $keyActualM->bobot_planning; - // }else if($keyActualM->qty_actual == 0){ - // $progressActualWeek = $keyActualM->bobot_planning; - // }else if($keyActualM->qty_plan == $keyActualM->sum_qty_actual){ - $progressActualWeek = $keyActualM[0]->bobot_planning / $keyActualM[0]->count_report; - // }else { - // $progressActualWeek = $progressActualWeek; - // } - // $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; - // jika report lebih dari 1 x, maka harusnya di bagi sabanyak jumlah report, - // contoh ada 3 report, report ke 1 adalah 5 maka 100/3 dan di looping + // $startPlan = new DateTime($keyPlanM->planned_start); + // $endPlan = new DateTime($keyPlanM->planned_end); + // $interval = $startPlan->diff($endPlan); + + // // Mengambil hasil selisih hari + // $duration = $interval->days; + // 2023-07-26 + $progressPlanWeek = $keyPlanM->bobot_planning / $duration; + $dataActivityPlan[] = array( + 'progressPlanDay' => $progressPlanWeek, + 'name' => $keyPlanM->name, + 'bobot_p' => $keyPlanM->bobot_planning, + 'duration' => $keyPlanM->duration + ); + $tmpProgressPlanWeek += $progressPlanWeek; } - else{ - $progressActualWeek = $progressActualWeek > ($keyActualM[0]->bobot_planning*95)/100 ? ($keyActualM[0]->bobot_planning*95)/100 : $progressActualWeek; + // } + + // hitung progress actual + // if (count($dataActualM) > 0 && count($dataActualM[0]) > 0) { + foreach ($dataActualM as $keyActualM) { + # hitung untuk persentase progress actual + // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; + // jika total report > dari planning + if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; + }else{ + // jika total report < dari planning + // $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; + if($keyActualM->qty_actual == 0){ + $progressActualWeek = 0; + }else{ + $progressActualWeek = ($keyActualM->qty_actual / $keyActualM->qty_plan) * $keyActualM->bobot_planning; + } + } + if($keyActualM->status_activity == 'done'){ + // if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ + + // } + // if($progressActualWeek > $keyActualM->bobot_planning){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_actual == 0){ + // $progressActualWeek = $keyActualM->bobot_planning; + // }else if($keyActualM->qty_plan == $keyActualM->sum_qty_actual){ + $progressActualWeek = $keyActualM->bobot_planning / $keyActualM->count_report; + // }else { + // $progressActualWeek = $progressActualWeek; + // } + // $progressActualWeek = $progressActualWeek > $keyActualM->bobot_planning ? $keyActualM->bobot_planning : $progressActualWeek; + // jika report lebih dari 1 x, maka harusnya di bagi sabanyak jumlah report, + // contoh ada 3 report, report ke 1 adalah 5 maka 100/3 dan di looping + } + else{ + $progressActualWeek = $progressActualWeek > ($keyActualM->bobot_planning*95)/100 ? ($keyActualM->bobot_planning*95)/100 : $progressActualWeek; + } + $dataActivityActual[] = array( + 'progressActualDay' => $progressActualWeek, + 'qty_act' => $keyActualM->qty_actual, + 'bobot_p' => $keyActualM->bobot_planning, + 'qty_plan' => $keyActualM->qty_plan, + 'status_activity' => $keyActualM->status_activity, + 'sum_qty_actual' => $keyActualM->sum_qty_actual, + 'name' => $keyActualM->name + ); + + $tmpProgressActualWeek += $progressActualWeek; } - $dataActivityActual[] = array( - 'progressActualDay' => $progressActualWeek, - 'qty_act' => $keyActualM[0]->qty_actual, - 'bobot_p' => $keyActualM[0]->bobot_planning, - 'qty_plan' => $keyActualM[0]->qty_plan, - 'status_activity' => $keyActualM[0]->status_activity, - 'sum_qty_actual' => $keyActualM[0]->sum_qty_actual, - 'name' => $keyActualM[0]->name - ); - - $tmpProgressActualWeek += $progressActualWeek; - } - } + // } $dataActivityPlanDate[] = array( "date" => $loopDay, From 837d96df5fb06002aa1d18524150c9b350e4ec6c Mon Sep 17 00:00:00 2001 From: wahyu Date: Mon, 4 Dec 2023 17:04:16 +0700 Subject: [PATCH 021/155] check 0 array on calculate scurve --- app/Helpers/MasterFunctionsHelper.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index dfc4d89..59c795f 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -1448,6 +1448,9 @@ class MasterFunctionsHelper // if($keyPlanM->duration == 0){ // $duration = 2; // Tanggal awal + if (count($keyPlanM) == 0) { + continue; + } $startDate = new DateTime($keyPlanM[0]->planned_start); // Tanggal akhir $endDate = new DateTime($keyPlanM[0]->planned_end); @@ -1479,6 +1482,9 @@ class MasterFunctionsHelper // hitung progress actual if (count($dataActualM) > 0 && count($dataActualM[0]) > 0) { foreach ($dataActualM as $keyActualM) { + if (count($keyPlanM) == 0) { + continue; + } # hitung untuk persentase progress actual // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; // jika total report > dari planning From 07a14558933cb04d9bfa253e709ad4c1485e6d68 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 5 Dec 2023 08:24:08 +0700 Subject: [PATCH 022/155] update endpoint --- .../ProjectCarausellController.php | 39 ++++++------------- 1 file changed, 11 insertions(+), 28 deletions(-) diff --git a/app/Http/Controllers/ProjectCarausellController.php b/app/Http/Controllers/ProjectCarausellController.php index 2850318..e64aca9 100644 --- a/app/Http/Controllers/ProjectCarausellController.php +++ b/app/Http/Controllers/ProjectCarausellController.php @@ -16,34 +16,19 @@ class ProjectCarausellController extends Controller $projectData = Project::query() ->select("id","nama","kode_sortname","pm_id","budget_health","calculation_status","mulai_proyek","akhir_proyek","rencana_biaya","company","scurve") ->get(); - $projectRisk = ProjectRisks::query() - ->select('proyek_id','description','level_risk','preventive_risk') - ->get(); - $projectIssue = ProjectIssues::query() - ->select('proyek_id','description','level_issue') - ->get(); $arr = []; foreach($projectData as $project) { - $riskProject = []; - $issueProject = []; - foreach ($projectRisk as $risk) { - if ($risk['proyek_id'] === $project['id']) { - $riskProject[] = [ - 'level_risk' => $risk['level_risk'], - 'preventive_risk' => $risk['preventive_risk'], - 'description' => $risk['description'] - ]; - } - } - foreach ($projectIssue as $issue) { - if ($issue['proyek_id'] === $project['id']) { - $issueProject[] = [ - 'level_issue' => $issue['level_issue'], - 'description' => $issue['description'] - ]; - } - } + $projectRisk = ProjectRisks::query() + ->select('proyek_id','description','level_risk','preventive_risk') + ->where('proyek_id', $project['id']) + ->get() + ->toArray(); + $projectIssue = ProjectIssues::query() + ->select('proyek_id','description','level_issue') + ->where('proyek_id',$project['id']) + ->get() + ->toArray(); $ganttData = VersionGantt::query() ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id','calculation_type') ->where('proyek_id',$project['id']) @@ -63,11 +48,9 @@ class ProjectCarausellController extends Controller "rencana_biaya" => $project['rencana_biaya'], "company" => $project['company'], "scurve" => $project['scurve'], - "project_risk" => $riskProject, - "project_issues" => $issueProject ], "project_manager" => $projectManager, - "project_risk" => $riskProject, + "project_risk" => $projectRisk, "project_issue" => $projectIssue, "gantt"=> $ganttData ]; From e7dd76c5a5d7c4185088729b1c60057164d32eb0 Mon Sep 17 00:00:00 2001 From: ibnu Date: Tue, 5 Dec 2023 11:22:44 +0700 Subject: [PATCH 023/155] update fix diff today, and fix round progress hirarchy, and fix estimated finish --- .../Commands/CalculateProgressGantt.php | 2 +- app/Helpers/MasterFunctionsHelper.php | 40 ++++++++++--------- app/Http/Controllers/ProjectController.php | 32 ++++++++++----- 3 files changed, 45 insertions(+), 29 deletions(-) diff --git a/app/Console/Commands/CalculateProgressGantt.php b/app/Console/Commands/CalculateProgressGantt.php index 5ac1e5f..f3b40c9 100644 --- a/app/Console/Commands/CalculateProgressGantt.php +++ b/app/Console/Commands/CalculateProgressGantt.php @@ -22,7 +22,7 @@ class CalculateProgressGantt extends Command $data = MasterFunctionsHelper::calculateSCurveForProgressTree($hierarchy_id); $hierarchy->bobot_planning = 100; - $hierarchy->progress =((int) end($data[0]['data']['percentageReal']) / (int) end($data[0]['data']['percentagePlan'])) * 100; + $hierarchy->progress =round(((int) end($data[0]['data']['percentageReal']) / (int) end($data[0]['data']['percentagePlan'])) * 100, 2); $hierarchy->save(); } } diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index acf3f69..805c01d 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -468,9 +468,9 @@ class MasterFunctionsHelper } if ($dataHeader) { - $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); + // $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); } else { - $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); + // $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['id'])->sum("rencana_biaya"); } if (!Activity::where("version_gantt_id", $keyGantt['id'])->first()) @@ -506,16 +506,16 @@ class MasterFunctionsHelper } $period = new \DatePeriod($begin, $interval, $end); - $arr_ActualM = []; + // $arr_ActualM = []; $tempDate = []; - $tempPercentagePlan = []; - $tempPercentagePlanWhr = []; - $tempPercentageReal = []; - $tempTtlPercentPlan = 0; - $tempTtlPercentActual = 0; + // $tempPercentagePlan = []; + // $tempPercentagePlanWhr = []; + // $tempPercentageReal = []; + // $tempTtlPercentPlan = 0; + // $tempTtlPercentActual = 0; - $currentACWP = 0; - $currentBCWP = 0; + // $currentACWP = 0; + // $currentBCWP = 0; $dataActivityPlanDate = []; $progressPlanKomulatifWeek = []; $progressActualKomulatifWeek = []; @@ -551,11 +551,15 @@ class MasterFunctionsHelper $dataActivityPlan = []; $dataActivityActual = []; - $today = new DateTime(); + $today = date('Y-m-d'); + $statusCutOfDate = false; + // if (new \DateTime($loopDay) < $today) { + // $statusCutOfDate = true; + // } if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); - if (new \DateTime($loopDay) < $today) { + if (new \DateTime($loopDay . ' Friday') <= new \DateTime($today . ' Friday')) { // $tempPercentageReal[] = round($tempTtlPercentActual, 2); $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); } @@ -599,7 +603,7 @@ class MasterFunctionsHelper // $progressActualWeek = ((((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*100)*$keyActualM->bobot_planning)/100; // jika total report > dari planning if($keyActualM->sum_qty_actual > $keyActualM->qty_plan){ - $progressActualWeek = (($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) *$keyActualM->bobot_planning/100; + $progressActualWeek = ($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * $keyActualM->bobot_planning; }else{ // jika total report < dari planning // $progressActualWeek = ((($keyActualM->qty_actual / $keyActualM->sum_qty_actual) * 100) / $keyActualM->qty_plan)*$keyActualM->bobot_planning; @@ -1431,11 +1435,11 @@ class MasterFunctionsHelper $dataActivityPlan = []; $dataActivityActual = []; - $today = new DateTime(); + $today = date('Y-m-d'); if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); - if (new \DateTime($loopDay) < $today) { + if (new \DateTime($loopDay . ' Friday') <= new \DateTime($today . ' Friday')) { // $tempPercentageReal[] = round($tempTtlPercentActual, 2); $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); } @@ -1681,11 +1685,11 @@ class MasterFunctionsHelper $dataActivityPlan = []; $dataActivityActual = []; - $today = new DateTime(); + $today = date('Y-m-d'); if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ - $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); - if (new \DateTime($loopDay) < $today) { + $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); + if (new \DateTime($loopDay . ' Friday') <= new \DateTime($today . ' Friday')) { // $tempPercentageReal[] = round($tempTtlPercentActual, 2); $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); } diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 737c648..66f4724 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -538,16 +538,26 @@ class ProjectController extends Controller $actualStartExist = Activity::where('proyek_id', $id)->whereNotNull('actual_start')->exists(); if($result['type_proyek_id'] === 9) { - $actualEndExist = Activity::where('proyek_id', $id)->exists(); - $query = Activity::where('proyek_id', $id); + // $actualEndExist = Activity::where('proyek_id', $id)->exists(); + // $query = Activity::where('proyek_id', $id); + $maxEndDate = Activity::where('proyek_id', $id)->select('end_date') + ->orderBy('end_date', 'desc') + ->first(); + }else{ - $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') + ->orderBy('end_date', 'desc') + ->first(); $query = Activity::where('version_gantt_id', $ganttId); } } else { $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $ganttId)->first(); $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); - $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') + ->orderBy('end_date', 'desc') + ->first(); $query = Activity::where('version_gantt_id', $ganttId); } @@ -556,11 +566,13 @@ class ProjectController extends Controller } else { $startDate = $query->orderBy('start_date')->value('start_date'); } - if($actualEndExist) - { - $maxEndDate = $query->max('id'); - $endDate = $query->where('id',$maxEndDate)->first()->end_date; - } + // if($actualEndExist) + // { + // // $maxEndDate = $query->max('id'); + // // get last end_date + // // $endDate = $query->where('id',$maxEndDate)->first()->end_date; + + // } $plannedStart = Activity::where('version_gantt_id', $ganttId) ->orderBy('planned_start') @@ -569,7 +581,7 @@ class ProjectController extends Controller ->orderByDesc('planned_end') ->value('planned_end'); $result->header->start_date = $startDate; - $result->header->end_date = $endDate; + $result->header->end_date = $maxEndDate->end_date; $result->header->planned_start = $plannedStart; $result->header->planned_end = $plannedEnd; return response()->json(['status'=>'success','code'=> 200,'data'=>$result, 'gantt'=>$ganttId], 200); From 1b52345f54083f985f3f7755d94f3fa0c0041a4d Mon Sep 17 00:00:00 2001 From: ibnu Date: Tue, 5 Dec 2023 13:05:43 +0700 Subject: [PATCH 024/155] update fix quick --- app/Http/Controllers/ProjectController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 66f4724..62bd9ab 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -539,7 +539,7 @@ class ProjectController extends Controller if($result['type_proyek_id'] === 9) { // $actualEndExist = Activity::where('proyek_id', $id)->exists(); - // $query = Activity::where('proyek_id', $id); + $query = Activity::where('proyek_id', $id); $maxEndDate = Activity::where('proyek_id', $id)->select('end_date') ->orderBy('end_date', 'desc') ->first(); From 1046904ea508839437400017ac19899f49dc8c2d Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 5 Dec 2023 14:00:21 +0700 Subject: [PATCH 025/155] update company_id and all_project access --- app/Models/ChecklistK3.php | 13 +++++++------ app/Models/Role.php | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/app/Models/ChecklistK3.php b/app/Models/ChecklistK3.php index a328fc7..564563f 100644 --- a/app/Models/ChecklistK3.php +++ b/app/Models/ChecklistK3.php @@ -12,11 +12,12 @@ class ChecklistK3 extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'name', - 'description', - 'created_at', - 'created_by', - 'updated_at', - 'updated_by' + 'name', + 'description', + 'created_at', + 'created_by', + 'updated_at', + 'updated_by', + 'company_id' ]; } diff --git a/app/Models/Role.php b/app/Models/Role.php index 4fdc897..09b75d2 100644 --- a/app/Models/Role.php +++ b/app/Models/Role.php @@ -12,6 +12,6 @@ class Role extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'name', 'description', 'default_page', 'created_at', 'created_by', 'updated_at', 'updated_by', 'company_id' + 'name', 'description', 'default_page', 'created_at', 'created_by', 'updated_at', 'updated_by', 'company_id', 'all_project' ]; } From a0a8b1b752edba3b17e0d1978f597173d583187f Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 6 Dec 2023 16:35:42 +0700 Subject: [PATCH 026/155] update filter company_id for dashboard and project --- .../Controllers/DashboardBoDController.php | 117 +++++++++++++----- app/Models/Project.php | 3 +- routes/web.php | 2 +- 3 files changed, 88 insertions(+), 34 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index deb8065..aca1727 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -41,49 +41,105 @@ class DashboardBoDController extends Controller private function getInvoiceIntegration($search) { - if(empty($search)) - return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); + if (empty($search)) + return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw').'/project_cost?project_no=SEARCH'); + $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); $token = config('api.adw_token'); $response = $this->curlReq($url, $token); - if(@$response->data->project_no == "") + if (@$response->data->project_no == "") return null; return $response; } - // to do - public function getCompanyCashFlow($year = '%') + // OLD + // public function getCompanyCashFlow($year = '%') + // { + // $year = $this->interpolateYear($year); + // $totalExpenditure = $totalInvoice = $totalPaidInvoice = 0; + + + // $totalBudgets = Project::select(DB::raw('SUM(CAST("rencana_biaya" AS DOUBLE PRECISION))')) + // ->where('mulai_proyek', 'like', $year) + // /* ->orWhere('akhir_proyek', 'like', $year) */ + // ->pluck('sum') + // ->first(); + + // $projects = Project::where('mulai_proyek', 'like', $year) + // /* ->orWhere('akhir_proyek', 'like', $year) */ + // ->get(); + // foreach ($projects as $project) { + // $project->expenses = 0; + + // $resp = null; + // if ($project->kode_sortname != "") { + // $resp = $this->getInvoiceIntegration($project->kode_sortname); + // /* $resp = $project->kode_sortname; */ + // $cost = $resp->data->total_cost ?? 0; + // $cost = substr($cost, 0, strpos($cost, ".")); + // $totalExpenditure += (int) $cost; + // $totalInvoice += $resp->data->total_invoice_amount ?? 0; + // $totalPaidInvoice += $resp->data->total_invoice_paid_amount ?? 0; + // } + + // } + + // return response()->json([ + // 'data' => [ + // 'total_budget' => (int) $totalBudgets ?? 0, + // 'total_expenditure' => $totalExpenditure, + // 'total_invoice' => $totalInvoice, + // 'total_paid_invoice' => $totalPaidInvoice, + // ] + // ], 200); + // } + + public function getCompanyCashFlow($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); $totalExpenditure = $totalInvoice = $totalPaidInvoice = 0; - // we can't use eloquent's sum() method because someone decided to use varchar as datatype in rencana_biaya field - $totalBudgets = Project::select(DB::raw('SUM(CAST("rencana_biaya" AS DOUBLE PRECISION))')) - ->where('mulai_proyek', 'like', $year) - /* ->orWhere('akhir_proyek', 'like', $year) */ - ->pluck('sum') - ->first(); + $totalBudgets = null; + if ($all_project) { + $totalBudgets = Project::where('mulai_proyek', 'like', $year) + ->where('company_id', $company_id) + ->sum(DB::raw('CAST("rencana_biaya" AS DOUBLE PRECISION)')); + } else { + $totalBudgets = Project::where('mulai_proyek', 'like', $year) + ->where('created_by_id', $hierarchy) + ->sum(DB::raw('CAST("rencana_biaya" AS DOUBLE PRECISION)')); + } + + $projects = null; + if ($all_project) { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('company_id', $company_id) + ->get(); + } else { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('created_by_id', $hierarchy) + ->get(); + } - $projects = Project::where('mulai_proyek', 'like', $year) - /* ->orWhere('akhir_proyek', 'like', $year) */ - ->get(); foreach ($projects as $project) { $project->expenses = 0; - $resp = null; if ($project->kode_sortname != "") { + $resp = $this->getInvoiceIntegration($project->kode_sortname); - /* $resp = $project->kode_sortname; */ $cost = $resp->data->total_cost ?? 0; $cost = substr($cost, 0, strpos($cost, ".")); - $totalExpenditure += (int) $cost; - $totalInvoice += $resp->data->total_invoice_amount ?? 0; - $totalPaidInvoice += $resp->data->total_invoice_paid_amount ?? 0; + $cost = 0; + $totalExpenditure = 0; + $totalInvoice = 0; + $totalPaidInvoice = 0; + + // $totalExpenditure += (int) $cost; + // $totalInvoice += $resp->data->total_invoice_amount ?? 0; + // $totalPaidInvoice += $resp->data->total_invoice_paid_amount ?? 0; } - } return response()->json([ @@ -96,6 +152,7 @@ class DashboardBoDController extends Controller ], 200); } + public function getInvoiceOutstanding($year = '%') { $year = $this->interpolateYear($year); @@ -147,15 +204,13 @@ class DashboardBoDController extends Controller } $selisihProgress = $planningProgress - $actualProgress; try { - if ($selisihProgress > 0 && $selisihProgress <= 5){ + if ($selisihProgress > 0 && $selisihProgress <= 5) { $return['warning'] += 1; $projects[$index]->status = 'warning'; - } - elseif ($selisihProgress == 0){ + } elseif ($selisihProgress == 0) { $return['on-schedule'] += 1; $projects[$index]->status = 'on-schedule'; - } - else { + } else { $return['behind-schedule'] += 1; $projects[$index]->status = 'behind-schedule'; } @@ -191,13 +246,11 @@ class DashboardBoDController extends Controller $actualProgress = !empty($actualArray) ? $actualArray[count($actualArray) - 1] : 0; } $selisihProgress = $planningProgress - $actualProgress; - if ($selisihProgress > 0 && $selisihProgress <= 5){ + if ($selisihProgress > 0 && $selisihProgress <= 5) { $warning++; - } - elseif ($selisihProgress == 0){ + } elseif ($selisihProgress == 0) { $onSchedule++; - } - else { + } else { $behindSchedule++; } } @@ -294,7 +347,7 @@ class DashboardBoDController extends Controller { $year = $this->interpolateYear($year); - $divisions = Divisi::select('id', 'name','parent','color') + $divisions = Divisi::select('id', 'name', 'parent', 'color') ->with('children') ->whereNull('parent') ->get(); diff --git a/app/Models/Project.php b/app/Models/Project.php index 115c9b6..43c0a1e 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -48,6 +48,7 @@ class Project extends Model 'created_by', 'updated_at', 'updated_by', - 'created_by_id' + 'created_by_id', + 'company_id' ]; } diff --git a/routes/web.php b/routes/web.php index 3976c2b..f7d3f5f 100644 --- a/routes/web.php +++ b/routes/web.php @@ -23,7 +23,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->group(['middleware' => ['auth', 'cors']], function () use ($router) { - $router->get('/dashboard/get-company-cashflow[/{year}]', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure + $router->get('/dashboard/get-company-cashflow/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure $router->get('/dashboard/get-invoice-outstanding[/{year}]', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in $router->get('/dashboard/get-total-project-per-schedule-health[/{year}]', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); $router->get('/dashboard/get-total-project-per-budget-health[/{year}]', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); From 4b7c97ba0d96fe472fbc3286ab7cdc88ae20561c Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 6 Dec 2023 17:33:51 +0700 Subject: [PATCH 027/155] update filter dashboard --- .../Controllers/DashboardBoDController.php | 32 +++++++++++++++---- routes/web.php | 4 +-- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index aca1727..a57d1d8 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -179,7 +179,7 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerScheduleHealth($year = '%') + public function getTotalProjectPerScheduleHealth($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); @@ -189,7 +189,17 @@ class DashboardBoDController extends Controller 'on-schedule' => 0, ]; - $projects = Project::where('mulai_proyek', 'like', $year)->get(); + $projects = null; + if ($all_project) { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('company_id', $company_id) + ->get(); + } else { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('created_by_id', $hierarchy) + ->get(); + } + foreach ($projects as $index => $project) { $project->scurve = MasterFunctionsHelper::getSCurve($project->id); $selisihProgress = 0; @@ -319,15 +329,23 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerPhase($year = '%') + public function getTotalProjectPerPhase($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); $projectPhases = ProjectPhase::orderBy('order')->get(); foreach ($projectPhases as $phase) { - $phase->totalProject = Project::where('phase_id', $phase->id) - ->where('mulai_proyek', 'like', $year) - /* ->orWhere('akhir_proyek', 'like', $year) */ - ->count(); + + if ($all_project) { + $phase->totalProject = Project::where('phase_id', $phase->id) + ->where('mulai_proyek', 'like', $year) + ->where('company_id', $company_id) + ->count(); + } else { + $phase->totalProject = Project::where('phase_id', $phase->id) + ->where('mulai_proyek', 'like', $year) + ->where('created_by_id', $hierarchy) + ->count(); + } } return response()->json([ 'data' => [ diff --git a/routes/web.php b/routes/web.php index f7d3f5f..057d0e9 100644 --- a/routes/web.php +++ b/routes/web.php @@ -25,11 +25,11 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/dashboard/get-company-cashflow/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure $router->get('/dashboard/get-invoice-outstanding[/{year}]', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in - $router->get('/dashboard/get-total-project-per-schedule-health[/{year}]', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); + $router->get('/dashboard/get-total-project-per-schedule-health/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); $router->get('/dashboard/get-total-project-per-budget-health[/{year}]', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); $router->get('/dashboard/get-total-project-schedule-health-per-division[/{year}]', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); $router->get('/dashboard/get-total-project-budget-health-per-division[/{year}]', 'DashboardBoDController@getTotalProjectBudgetHealthPerDivision'); - $router->get('/dashboard/get-total-project-per-phase[/{year}]', 'DashboardBoDController@getTotalProjectPerPhase'); + $router->get('/dashboard/get-total-project-per-phase/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerPhase'); $router->get('/dashboard/get-total-project-per-division[/{year}]', 'DashboardBoDController@getTotalProjectPerDivision'); $router->get('/dashboard/get-total-project-value-per-division[/{year}]', 'DashboardBoDController@getTotalProjectValuePerDivision'); $router->get('/dashboard/get-detail-expenditure[/{year}]', 'DashboardBoDController@getDetailExpenditure'); From 6bb424b6fd63342cae93f2f5d8005e310ff8a15b Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 7 Dec 2023 16:10:25 +0700 Subject: [PATCH 028/155] update validation name --- app/Http/Controllers/DivisiController.php | 81 ++++++++++++----------- app/Http/Controllers/RoleController.php | 71 ++++++++++---------- 2 files changed, 78 insertions(+), 74 deletions(-) diff --git a/app/Http/Controllers/DivisiController.php b/app/Http/Controllers/DivisiController.php index 2d056aa..d46c927 100644 --- a/app/Http/Controllers/DivisiController.php +++ b/app/Http/Controllers/DivisiController.php @@ -8,21 +8,23 @@ use App\Models\Divisi; class DivisiController extends Controller { - private function getAllChildren($divisi, $depth = 0, $array = []) { + private function getAllChildren($divisi, $depth = 0, $array = []) + { $divisi->depth = $depth; array_push($array, $divisi); - foreach($divisi->children as $child){ + foreach ($divisi->children as $child) { $array = $this->getAllChildren($child, $depth + 1, $array); } return $array; } - public function add(Request $request){ + public function add(Request $request) + { $this->validate($request, [ - 'name' => 'string|required|unique:m_divisi,name', + 'name' => 'string|required|unique:m_divisi,name,NULL,id,company_id,' . $request->input('company_id'), 'description' => 'nullable|string', 'parent' => 'nullable|integer', - 'color'=>'nullable|string|max:10' + 'color' => 'nullable|string|max:10' ]); $data = $request->all(); @@ -30,15 +32,16 @@ class DivisiController extends Controller $result = Divisi::create($data); - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add data','code'=> 500]); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Failed to add data', 'code' => 500]); - return response()->json(['status'=>'success','message'=>'Data created!','code'=>200]); + 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); + 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); $this->validate($request, [ 'name' => 'string|required', @@ -47,46 +50,46 @@ class DivisiController extends Controller ]); $data = Divisi::find($id); - $request->name !== $data['name'] ? $this->validate($request,['name'=>'unique:m_divisi,name']) : ''; + $request->name !== $data['name'] ? $this->validate($request, ['name' => 'unique:m_divisi,name']) : ''; - if(!$data) - return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + 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); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Update failed!', 'code' => 500], 500); - return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); + 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); + 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); + 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); + if (!$delete) + return response()->json(['status' => 'failed', 'message' => 'Delete failed!', 'code' => 500], 500); - return response()->json(['status'=>'success','message'=> 'Data deleted!','code'=> 200], 200); + 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); + { + $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); //return $this->list(); // cant use builder for this case } @@ -95,20 +98,20 @@ class DivisiController extends Controller { $parentMenus = Divisi::whereNull('parent')->with('children')->get(); $divisions = []; - foreach($parentMenus as $menu){ + foreach ($parentMenus as $menu) { $childs = $this->getAllChildren($menu); - foreach($childs as $d){ + foreach ($childs as $d) { $d->displayName = ' ' . $d->name; - for($i=0; $i < $d->depth; $i++){ - $d->displayName = '--' . $d->displayName ; + for ($i = 0; $i < $d->depth; $i++) { + $d->displayName = '--' . $d->displayName; } array_push($divisions, $d); } } $countData = count($divisions); - if($countData == 0) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + if ($countData == 0) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - return response()->json(['status'=>'success','code'=>200,'data'=> $divisions, 'totalRecord'=> $countData], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $divisions, 'totalRecord' => $countData], 200); } } diff --git a/app/Http/Controllers/RoleController.php b/app/Http/Controllers/RoleController.php index 57b8c58..7e6dbde 100644 --- a/app/Http/Controllers/RoleController.php +++ b/app/Http/Controllers/RoleController.php @@ -11,76 +11,77 @@ class RoleController extends Controller public function add(Request $request) { $this->validate($request, [ - 'name' => 'string|required|unique:m_roles,name', + 'name' => 'string|required|unique:m_roles,name,NULL,id,company_id,' . $request->input('company_id'), 'description' => 'required' ]); $data = $request->all(); $data['created_by'] = $this->currentName; - if (!isset($data['default_page'])) { - $data['default_page'] = 29; // dashboard - } + if (!isset($data['default_page'])) { + $data['default_page'] = 29; // dashboard + } $result = Role::create($data); - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=>500], 500); + 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); + 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); + 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); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + 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); + if (empty($id) || !is_int((int)$id)) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); - $this->validate($request, [ - 'name' => 'string|required', - 'description' => 'required' + $this->validate($request, [ + 'name' => 'string|required', + 'description' => 'required' ]); $data = Role::find($id); - $request->name !== $data['name'] ? $this->validate($request,['name'=>'unique:m_roles,name']) : ''; + $request->name !== $data['name'] ? $this->validate($request, ['name' => 'unique:m_roles,name']) : ''; - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + 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); + 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); + 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); + 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); + 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); + 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); + return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); } public function search(Request $request) @@ -93,7 +94,7 @@ class RoleController extends Controller $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } public function list() @@ -101,9 +102,9 @@ class RoleController extends Controller $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); + 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); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data, 'totalRecord' => $countData], 200); } } From f2a88dd792f5cbf21eeaee5dc9953c4cd41f13ab Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 7 Dec 2023 16:10:44 +0700 Subject: [PATCH 029/155] update filter by_company --- .../Controllers/DashboardBoDController.php | 153 ++++++++++-------- 1 file changed, 86 insertions(+), 67 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index a57d1d8..9b77805 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -54,48 +54,6 @@ class DashboardBoDController extends Controller return $response; } - // OLD - // public function getCompanyCashFlow($year = '%') - // { - // $year = $this->interpolateYear($year); - // $totalExpenditure = $totalInvoice = $totalPaidInvoice = 0; - - - // $totalBudgets = Project::select(DB::raw('SUM(CAST("rencana_biaya" AS DOUBLE PRECISION))')) - // ->where('mulai_proyek', 'like', $year) - // /* ->orWhere('akhir_proyek', 'like', $year) */ - // ->pluck('sum') - // ->first(); - - // $projects = Project::where('mulai_proyek', 'like', $year) - // /* ->orWhere('akhir_proyek', 'like', $year) */ - // ->get(); - // foreach ($projects as $project) { - // $project->expenses = 0; - - // $resp = null; - // if ($project->kode_sortname != "") { - // $resp = $this->getInvoiceIntegration($project->kode_sortname); - // /* $resp = $project->kode_sortname; */ - // $cost = $resp->data->total_cost ?? 0; - // $cost = substr($cost, 0, strpos($cost, ".")); - // $totalExpenditure += (int) $cost; - // $totalInvoice += $resp->data->total_invoice_amount ?? 0; - // $totalPaidInvoice += $resp->data->total_invoice_paid_amount ?? 0; - // } - - // } - - // return response()->json([ - // 'data' => [ - // 'total_budget' => (int) $totalBudgets ?? 0, - // 'total_expenditure' => $totalExpenditure, - // 'total_invoice' => $totalInvoice, - // 'total_paid_invoice' => $totalPaidInvoice, - // ] - // ], 200); - // } - public function getCompanyCashFlow($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); @@ -128,9 +86,9 @@ class DashboardBoDController extends Controller $resp = null; if ($project->kode_sortname != "") { - $resp = $this->getInvoiceIntegration($project->kode_sortname); - $cost = $resp->data->total_cost ?? 0; - $cost = substr($cost, 0, strpos($cost, ".")); + // $resp = $this->getInvoiceIntegration($project->kode_sortname); + // $cost = $resp->data->total_cost ?? 0; + // $cost = substr($cost, 0, strpos($cost, ".")); $cost = 0; $totalExpenditure = 0; $totalInvoice = 0; @@ -152,7 +110,7 @@ class DashboardBoDController extends Controller ], 200); } - + // integrasi public function getInvoiceOutstanding($year = '%') { $year = $this->interpolateYear($year); @@ -232,9 +190,13 @@ class DashboardBoDController extends Controller return response()->json(['data' => $return, 'q' => $projects], 200); } - public function getTotalProjectScheduleHealthPerDivision($year = '%') + public function getTotalProjectScheduleHealthPerDivision($year = '%', $company_id) { $year = $this->interpolateYear($year); + $divisions = Divisi::whereNull('parent') + ->where('company_id', $company_id) + ->get(); + $divisions = Divisi::whereNull('parent')->get(); foreach ($divisions as $index => $division) { @@ -277,16 +239,62 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerBudgetHealth($year = '%') + public function getTotalProjectPerBudgetHealth($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); - return response()->json([ + $response = [ 'data' => [ - 'overrun' => Project::where('mulai_proyek', 'like', $year)->where('budget_health', 'overrun')->count(), - 'warning' => Project::where('mulai_proyek', 'like', $year)->where('budget_health', 'warning')->count(), - 'on-budget' => Project::where('mulai_proyek', 'like', $year)->where('budget_health', 'on-budget')->count(), + 'overrun' => 0, + 'warning' => 0, + 'on-budget' => 0, ] - ], 200); + ]; + + if ($all_project) { + $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'overrun') + ->where('company_id', $company_id) + ->count(); + } else { + $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'overrun') + ->where('created_by_id', $hierarchy) + ->count(); + } + if ($all_project) { + $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'overrun') + ->where('company_id', $company_id) + ->count(); + } else { + $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'overrun') + ->where('created_by_id', $hierarchy) + ->count(); + } + if ($all_project) { + $response['data']['warning'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'warning') + ->where('company_id', $company_id) + ->count(); + } else { + $response['data']['warning'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'warning') + ->where('created_by_id', $hierarchy) + ->count(); + } + if ($all_project) { + $response['data']['on-budget'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'on-budget') + ->where('company_id', $company_id) + ->count(); + } else { + $response['data']['on-budget'] = Project::where('mulai_proyek', 'like', $year) + ->where('budget_health', 'on-budget') + ->where('created_by_id', $hierarchy) + ->count(); + } + return response()->json($response, 200); } private function countTotalProjectByBudgetHealthInDivision($divisi, $year, $health) @@ -299,12 +307,13 @@ class DashboardBoDController extends Controller } - public function getTotalProjectBudgetHealthPerDivision($year = '%') + public function getTotalProjectBudgetHealthPerDivision($year = '%', $company_id) { $year = $this->interpolateYear($year); $divisions = Divisi::select('id', 'name') ->with('children') ->whereNull('parent') + ->where('company_id', $company_id) ->get(); // to do : count in more than 1 level child foreach ($divisions as $division) { @@ -332,7 +341,7 @@ class DashboardBoDController extends Controller public function getTotalProjectPerPhase($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); - $projectPhases = ProjectPhase::orderBy('order')->get(); + $projectPhases = ProjectPhase::where('company_id', $company_id)->orderBy('order')->get(); foreach ($projectPhases as $phase) { if ($all_project) { @@ -361,15 +370,17 @@ class DashboardBoDController extends Controller ->count(); } - public function getTotalProjectPerDivision($year = '%') + public function getTotalProjectPerDivision($year = '%', $company_id) { $year = $this->interpolateYear($year); $divisions = Divisi::select('id', 'name', 'parent', 'color') ->with('children') ->whereNull('parent') + ->where('company_id', $company_id) ->get(); + // to do : count in more than 1 level child foreach ($divisions as $v) { $v->total = $this->countTotalProjectInDivision($v->id, $year); @@ -394,16 +405,16 @@ class DashboardBoDController extends Controller ->first(); } - public function getTotalProjectValuePerDivision($year = '%') + public function getTotalProjectValuePerDivision($year = '%', $company_id) { $year = $this->interpolateYear($year); - $divisions = Divisi::select('id', 'name', 'color') + $divisions = Divisi::select('id', 'name', 'color') ->with('children') ->whereNull('parent') + ->where('company_id', $company_id) ->get(); - // to do : count in more than 1 level child foreach ($divisions as $v) { $v->total = $this->countTotalProjectValueInDivision($v->id, $year); foreach ($v->children as $d) { @@ -418,21 +429,29 @@ class DashboardBoDController extends Controller } - public function getDetailExpenditure($year = '%') + public function getDetailExpenditure($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); - $projects = Project::where('mulai_proyek', 'like', $year) - /* ->orWhere('akhir_proyek', 'like', $year) */ - ->orderBy('id', 'desc') - ->get(); + $projects = null; + if ($all_project) { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('company_id', $company_id) + ->orderBy('id', 'desc') + ->get(); + } else { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('created_by_id', $hierarchy) + ->orderBy('id', 'desc') + ->get(); + } + foreach ($projects as $project) { $lastGantt = MasterFunctionsHelper::getLatestGantt($project->id); if ($project->kode_sortname != "") { - $resp = $this->getInvoiceIntegration($project->kode_sortname); $project->invoice = [ - 'invoiced' => $resp->data->total_invoice_amount ?? 0, - 'paid' => $resp->data->total_invoice_paid_amount ?? 0, + 'invoiced' => 0, + 'paid' => 0, ]; } From fb55b6d14ec9ec96e26b68fd6749d161c2dc30d7 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 7 Dec 2023 16:10:57 +0700 Subject: [PATCH 030/155] update new response --- .../Controllers/VersionGanttController.php | 98 ++++++++++--------- 1 file changed, 51 insertions(+), 47 deletions(-) diff --git a/app/Http/Controllers/VersionGanttController.php b/app/Http/Controllers/VersionGanttController.php index c5fabab..37cb585 100644 --- a/app/Http/Controllers/VersionGanttController.php +++ b/app/Http/Controllers/VersionGanttController.php @@ -14,7 +14,8 @@ use App\Models\ActivityProgressLog; class VersionGanttController extends Controller { - public function add(Request $request){ + public function add(Request $request) + { $this->validate($request, [ 'name_version' => 'required', 'proyek_id' => 'required' @@ -23,30 +24,31 @@ class VersionGanttController extends Controller $data['created_by'] = $this->currentName; $result = VersionGantt::create($data); - if($result){ - return response()->json(['status'=>'success','message'=>'version gantt Project successfull created','code'=>200]); - }else{ - return response()->json(['status'=>'failed','message'=>'version gantt Project failed created','code'=>400]); + if ($result) { + return response()->json(['status' => 'success', 'message' => 'version gantt Project successfull created', 'code' => 200, 'id' => $result->id]); + } else { + return response()->json(['status' => 'failed', 'message' => 'version gantt Project failed created', 'code' => 400]); } } - public function update(Request $request, $id){ + public function update(Request $request, $id) + { - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + if (!$id || (int) $id < 0 || $id == "") { + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); } $data = VersionGantt::find($id); - if($data){ + if ($data) { $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data version gantt Project not found!','code'=>400], 400); + } else { + return response()->json(['status' => 'failed', 'message' => 'data version gantt Project not found!', 'code' => 400], 400); die(); } - if($result){ - return response()->json(['status'=>'success','message'=>'version gantt Project successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'version gantt Project failed updated!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'message' => 'version gantt Project successfully updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'version gantt Project failed updated!', 'code' => 400], 400); } } @@ -54,19 +56,19 @@ class VersionGanttController extends Controller { $data = VersionGantt::find($id); - if($data){ + if ($data) { $delete = $data->delete(); $this->deleteRelative($data['id']); - }else{ - return response()->json(['status'=>'failed','message'=>'data version gantt Project not found!','code'=>400], 400); + } else { + return response()->json(['status' => 'failed', 'message' => 'data version gantt Project not found!', 'code' => 400], 400); die(); } - if($delete){ - return response()->json(['status'=>'success','message'=>'version gantt Project successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'version gantt Project failed deleted!','code'=>400], 400); + if ($delete) { + return response()->json(['status' => 'success', 'message' => 'version gantt Project successfully deleted!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'version gantt Project failed deleted!', 'code' => 400], 400); } } @@ -81,18 +83,19 @@ class VersionGanttController extends Controller ActivityProgressLog::where('version_gantt_id', $version_gantt_id)->delete(); } - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','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 = VersionGantt::find($id); - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data version gantt, please try again later!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get data version gantt, please try again later!', 'code' => 400], 400); } } @@ -106,23 +109,24 @@ class VersionGanttController extends Controller $dataGet = $builder->get(); // $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet], 200); } - public function ganttProgress($column, $value){ - $progress = VersionGantt::select('m_version_gantt.id','m_activity.persentase_progress', 'm_activity.bobot_planning') - ->join('m_activity', 'm_version_gantt.id', '=', 'm_activity.version_gantt_id') - ->where("m_version_gantt.".$column, $value) - // ->where('m_activity.type_activity', "project") - ->where('m_activity.parent_id', null) - ->get(); - foreach($progress as $item) { - if($item->persentase_progress){ - $item->progress = $item->persentase_progress; - $item->bobot = $item->bobot_planning; - $item->save(); + public function ganttProgress($column, $value) + { + $progress = VersionGantt::select('m_version_gantt.id', 'm_activity.persentase_progress', 'm_activity.bobot_planning') + ->join('m_activity', 'm_version_gantt.id', '=', 'm_activity.version_gantt_id') + ->where("m_version_gantt." . $column, $value) + // ->where('m_activity.type_activity', "project") + ->where('m_activity.parent_id', null) + ->get(); + foreach ($progress as $item) { + if ($item->persentase_progress) { + $item->progress = $item->persentase_progress; + $item->bobot = $item->bobot_planning; + $item->save(); + } } - } } public function list() @@ -130,10 +134,10 @@ class VersionGanttController extends Controller $data = VersionGantt::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 version gantt, please try again later!','code'=>400], 400); + if ($data) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data, 'totalRecord' => $countData], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get list version gantt, please try again later!', 'code' => 400], 400); } } } From b43b9f465e2077d3a94245cbad39192d350dac41 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 7 Dec 2023 16:11:08 +0700 Subject: [PATCH 031/155] update url for dashboard --- routes/web.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/routes/web.php b/routes/web.php index 057d0e9..0d334f0 100644 --- a/routes/web.php +++ b/routes/web.php @@ -26,13 +26,13 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/dashboard/get-company-cashflow/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure $router->get('/dashboard/get-invoice-outstanding[/{year}]', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in $router->get('/dashboard/get-total-project-per-schedule-health/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); - $router->get('/dashboard/get-total-project-per-budget-health[/{year}]', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); - $router->get('/dashboard/get-total-project-schedule-health-per-division[/{year}]', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); - $router->get('/dashboard/get-total-project-budget-health-per-division[/{year}]', 'DashboardBoDController@getTotalProjectBudgetHealthPerDivision'); + $router->get('/dashboard/get-total-project-per-budget-health/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); + $router->get('/dashboard/get-total-project-schedule-health-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); + $router->get('/dashboard/get-total-project-budget-health-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectBudgetHealthPerDivision'); $router->get('/dashboard/get-total-project-per-phase/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerPhase'); - $router->get('/dashboard/get-total-project-per-division[/{year}]', 'DashboardBoDController@getTotalProjectPerDivision'); - $router->get('/dashboard/get-total-project-value-per-division[/{year}]', 'DashboardBoDController@getTotalProjectValuePerDivision'); - $router->get('/dashboard/get-detail-expenditure[/{year}]', 'DashboardBoDController@getDetailExpenditure'); + $router->get('/dashboard/get-total-project-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerDivision'); + $router->get('/dashboard/get-total-project-value-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectValuePerDivision'); + $router->get('/dashboard/get-detail-expenditure/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getDetailExpenditure'); $router->post('/role/search', 'RoleController@search'); $router->post('/role/add', 'RoleController@add'); From f7bb82f792f5f1f0354cc830b04cb99fba6bbf86 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Fri, 8 Dec 2023 15:16:59 +0700 Subject: [PATCH 032/155] update select customer role --- app/Http/Controllers/ProjectController.php | 27 ++++++++++++++-------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 3015327..ff9a3cf 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -503,20 +503,29 @@ class ProjectController extends Controller return response()->json(['status' => 'success', 'data' => $response, 'code' => 200], 200); } - public function getByUser($id) - { - $alias = "utp"; + public function getByUser($id) { $userProyek = UserToProyek::query() - ->from('assign_hr_to_proyek AS ' . $alias) + ->from('assign_hr_to_proyek AS ahtp') ->where([ ['is_customer', true], ['user_id', $id] ]) - ->leftJoin('m_users', $alias . '.user_id', '=', 'm_users.id') - ->leftJoin('m_proyek', $alias . '.proyek_id', '=', 'm_proyek.id') - ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') - ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name', 'm_users.name AS join_first_name') - ->get(); + ->leftJoin('m_users', 'ahtp.user_id', '=', 'm_users.id') + ->leftJoin('m_proyek AS mp', 'ahtp.proyek_id', '=', 'mp.id') + ->leftJoin('m_type_proyek', 'mp.type_proyek_id', '=', 'm_type_proyek.id') + ->select( + 'mp.id', + 'mp.nama', + 'mp.rencana_biaya', + 'mp.type_proyek_id', + 'mp.currency_symbol', + 'mp.mulai_proyek', + 'mp.akhir_proyek', + 'm_users.name AS join_first_name', + 'm_users.username AS join_first_username', + 'm_type_proyek.name AS join_second_name', + 'm_type_proyek.name AS join_second_description' + )->get(); $totalRecord = $userProyek->count(); return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); From aded36c0ae3f3e02ac4087727b0528eaec783201 Mon Sep 17 00:00:00 2001 From: ibnu Date: Tue, 12 Dec 2023 07:16:34 +0700 Subject: [PATCH 033/155] update for logic update status report on-progress, actual >= plan is 95, actual < plan is calculate --- .../Controllers/ReportActivityMaterialController.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index e451129..1712b5b 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -64,10 +64,18 @@ class ReportActivityMaterialController extends Controller } else { $sumAssignMaterial = AssignMaterial::where('activity_id', $request->activity_id)->sum('qty_planning'); $sumReportActivityMaterial = ReportActivityMaterial::where('activity_id', $request->activity_id)->sum('qty'); + // if actual >= plan + if ($sumReportActivityMaterial >= $sumAssignMaterial){ + $persentaseProgress = 95; + }else{ + // actual < plan + $persentaseProgress = $sumReportActivityMaterial/$sumAssignMaterial*100; + } + $dataUpdate = array( "actual_start" => null, - "actual_end" => null, - "persentase_progress" => $sumReportActivityMaterial/$sumAssignMaterial*100, + "actual_end" => null, + "persentase_progress" => $persentaseProgress, "updated_by" => $this->currentName ); if ($sumReportActivityMaterial > 0) { From 67da512ce725fa0f1f14e534c19caad4de602188 Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 13 Dec 2023 20:36:12 +0700 Subject: [PATCH 034/155] update filter project by company --- .../ProjectCarausellController.php | 40 +++++++++++++------ routes/web.php | 2 +- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/app/Http/Controllers/ProjectCarausellController.php b/app/Http/Controllers/ProjectCarausellController.php index e64aca9..6abd158 100644 --- a/app/Http/Controllers/ProjectCarausellController.php +++ b/app/Http/Controllers/ProjectCarausellController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use Illuminate\Http\Request; use App\Models\{ User, Project, @@ -9,33 +10,46 @@ use App\Models\{ ProjectIssues, ProjectRisks }; + class ProjectCarausellController extends Controller { - public function invoke() { + public function invoke(Request $request) + { // Master Data - $projectData = Project::query() - ->select("id","nama","kode_sortname","pm_id","budget_health","calculation_status","mulai_proyek","akhir_proyek","rencana_biaya","company","scurve") - ->get(); + $company_id = $request->route('company_id'); + $all_project = $request->route('all_project'); + $hierarchy = $request->route('hierarchy'); + + $query = Project::query() + ->select("id", "nama", "kode_sortname", "pm_id", "budget_health", "calculation_status", "mulai_proyek", "akhir_proyek", "rencana_biaya", "company", "scurve"); + + if ($all_project) { + $query->where('company_id', $company_id); + } else { + $query->where('created_by_id', $hierarchy); + } + + $projectData = $query->get(); $arr = []; - foreach($projectData as $project) { + foreach ($projectData as $project) { $projectRisk = ProjectRisks::query() - ->select('proyek_id','description','level_risk','preventive_risk') + ->select('proyek_id', 'description', 'level_risk', 'preventive_risk') ->where('proyek_id', $project['id']) ->get() ->toArray(); $projectIssue = ProjectIssues::query() - ->select('proyek_id','description','level_issue') - ->where('proyek_id',$project['id']) + ->select('proyek_id', 'description', 'level_issue') + ->where('proyek_id', $project['id']) ->get() ->toArray(); $ganttData = VersionGantt::query() - ->select('id', 'name_version','hierarchy_ftth_id','cost_to_complete','proyek_id','calculation_type') - ->where('proyek_id',$project['id']) + ->select('id', 'name_version', 'hierarchy_ftth_id', 'cost_to_complete', 'proyek_id', 'calculation_type') + ->where('proyek_id', $project['id']) ->orderByDesc('id') ->first(); $projectManager = User::where('id', $project['pm_id'])->value('name'); - $arr[]= [ + $arr[] = [ "project" => [ "id" => $project['id'], "pm_id" => $project['pm_id'], @@ -52,9 +66,9 @@ class ProjectCarausellController extends Controller "project_manager" => $projectManager, "project_risk" => $projectRisk, "project_issue" => $projectIssue, - "gantt"=> $ganttData + "gantt" => $ganttData ]; } - return response()->json(['status'=>'success','code'=> 200,'data'=> $arr, "total_project"=>count($arr)], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $arr, "total_project" => count($arr)], 200); } } diff --git a/routes/web.php b/routes/web.php index 0d334f0..77ce518 100644 --- a/routes/web.php +++ b/routes/web.php @@ -81,7 +81,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro /* $router->get('/project/get-status-health-schedule/{id}', 'ProjectController@getStatusSchedule'); */ /* $router->get('/project/get-status-health-budget/{id}', 'ProjectController@getStatusBudget'); */ - $router->get('/project-carausell', 'ProjectCarausellController@invoke'); + $router->get('/project-carausell/{company_id}/{all_project}/{hierarchy}', 'ProjectCarausellController@invoke'); $router->post('/project-charter/search', 'ProjectCharterController@search'); $router->post('/project-charter/add', 'ProjectCharterController@add'); From d1f1deac35e2fab60a4bbd8a8e896a0e3483ad12 Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 13 Dec 2023 21:48:39 +0700 Subject: [PATCH 035/155] update func getInvoiceOutstanding --- .../Controllers/DashboardBoDController.php | 22 +++++++++++++------ routes/web.php | 2 +- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index 9b77805..cabc763 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -111,22 +111,30 @@ class DashboardBoDController extends Controller } // integrasi - public function getInvoiceOutstanding($year = '%') + public function getInvoiceOutstanding($year = '%', $company_id, $all_project, $hierarchy) { $year = $this->interpolateYear($year); - $projects = Project::where('mulai_proyek', 'like', $year) - /* ->orWhere('akhir_proyek', 'like', $year) */ - ->get(); + $projects = null; + if ($all_project) { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('company_id', $company_id) + ->get(); + } else { + $projects = Project::where('mulai_proyek', 'like', $year) + ->where('created_by_id', $hierarchy) + ->get(); + } + $return = []; foreach ($projects as $project) { $resp = null; if ($project->kode_sortname != "") { - $resp = $this->getInvoiceIntegration($project->kode_sortname); + // $resp = $this->getInvoiceIntegration($project->kode_sortname); array_push($return, [ 'project' => $project->nama, 'project_code' => $project->kode_sortname, - 'invoiced' => $resp->data->total_invoice_amount ?? 0, - 'paid' => $resp->data->total_invoice_paid_amount ?? 0, + 'invoiced' => 0, + 'paid' => 0, 'response' => $resp, ]); } diff --git a/routes/web.php b/routes/web.php index 77ce518..4d69afb 100644 --- a/routes/web.php +++ b/routes/web.php @@ -24,7 +24,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->group(['middleware' => ['auth', 'cors']], function () use ($router) { $router->get('/dashboard/get-company-cashflow/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure - $router->get('/dashboard/get-invoice-outstanding[/{year}]', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in + $router->get('/dashboard/get-invoice-outstanding/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in $router->get('/dashboard/get-total-project-per-schedule-health/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); $router->get('/dashboard/get-total-project-per-budget-health/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); $router->get('/dashboard/get-total-project-schedule-health-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); From 1971cb56146d26228705cb64b56bf4269ff7739f Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 14 Dec 2023 10:34:16 +0700 Subject: [PATCH 036/155] update filter --- app/Http/Controllers/DashboardBoDController.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index cabc763..81c8830 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -203,12 +203,11 @@ class DashboardBoDController extends Controller $year = $this->interpolateYear($year); $divisions = Divisi::whereNull('parent') ->where('company_id', $company_id) + ->whereNull('parent') ->get(); - $divisions = Divisi::whereNull('parent')->get(); foreach ($divisions as $index => $division) { - $scheduleData = new Collection(); $behindSchedule = $warning = $onSchedule = 0; From 9b24833159c2dbfe1ce4fee2e094dbe568829293 Mon Sep 17 00:00:00 2001 From: wahyu Date: Fri, 15 Dec 2023 13:07:51 +0700 Subject: [PATCH 037/155] update report analysis --- app/Http/Controllers/ActivityController.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) mode change 100644 => 100755 app/Http/Controllers/ActivityController.php diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php old mode 100644 new mode 100755 index cbb425e..af5a636 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -697,7 +697,7 @@ class ActivityController extends Controller 'm_version_gantt.name_version', DB::raw('user_names.user_name as user_name'), DB::raw('SUM(report_activity_material.qty) as qty'), - 'assign_material_to_activity.qty_planning', + DB::raw('SUM(assign_material_to_activity.qty_planning) as qty_planning'), 'assign_material_to_activity.id as join_third_id' ) ->join('m_version_gantt', 'm_version_gantt.id', '=', 'selfTable.version_gantt_id') @@ -710,11 +710,9 @@ class ActivityController extends Controller GROUP BY activity_id) as user_names'), function ($join) { $join->on('user_names.activity_id', '=', 'selfTable.id'); }) + ->where('report_activity_material.assign_material_id', '=', DB::raw('assign_material_to_activity.id')) ->groupBy('selfTable.id') - ->groupBy('selfTable.name') - ->groupBy('selfTable.persentase_progress') ->groupBy('m_version_gantt.name_version') - ->groupBy('assign_material_to_activity.qty_planning') ->groupBy('assign_material_to_activity.id') ->groupBy('user_names.user_name') ->get(); From c8162ed09b0ac5d678fc4200a102ee61ac21074c Mon Sep 17 00:00:00 2001 From: wahyu Date: Mon, 18 Dec 2023 13:33:28 +0700 Subject: [PATCH 038/155] update report analysis --- app/Http/Controllers/ActivityController.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index af5a636..e08ff7b 100755 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -697,9 +697,10 @@ class ActivityController extends Controller 'm_version_gantt.name_version', DB::raw('user_names.user_name as user_name'), DB::raw('SUM(report_activity_material.qty) as qty'), - DB::raw('SUM(assign_material_to_activity.qty_planning) as qty_planning'), + // DB::raw('SUM(assign_material_to_activity.qty_planning) as qty_planning'), 'assign_material_to_activity.id as join_third_id' ) + ->addSelect(DB::raw('(SELECT SUM(assign_material_to_activity.qty_planning) FROM assign_material_to_activity WHERE assign_material_to_activity.activity_id = report_activity_material.activity_id) as qty_planning')) ->join('m_version_gantt', 'm_version_gantt.id', '=', 'selfTable.version_gantt_id') ->leftJoin('assign_hr_to_activity', 'assign_hr_to_activity.activity_id', '=', 'selfTable.id') ->leftJoin('report_activity_material', 'report_activity_material.activity_id', '=', 'selfTable.id') @@ -710,11 +711,12 @@ class ActivityController extends Controller GROUP BY activity_id) as user_names'), function ($join) { $join->on('user_names.activity_id', '=', 'selfTable.id'); }) - ->where('report_activity_material.assign_material_id', '=', DB::raw('assign_material_to_activity.id')) + ->where('assign_material_to_activity.id', '=', DB::raw('report_activity_material.assign_material_id')) ->groupBy('selfTable.id') ->groupBy('m_version_gantt.name_version') ->groupBy('assign_material_to_activity.id') ->groupBy('user_names.user_name') + ->groupBy('report_activity_material.activity_id') ->get(); return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet ], 200); } From af67a7a366e5b8e51ca435cb35421b6eb45eac2b Mon Sep 17 00:00:00 2001 From: wahyu Date: Mon, 18 Dec 2023 16:55:02 +0700 Subject: [PATCH 039/155] update handle double quotes --- app/Http/Controllers/ReportActivityMaterialController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index 1712b5b..d5fc160 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -143,7 +143,7 @@ class ReportActivityMaterialController extends Controller $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) - ->where('m.description', $materialName) + ->where('m.description', 'LIKE', '%' . $materialName . '%') ->orderBy('assign_material_to_activity.id', 'asc') ->get(); if ($baselineDuration > 0) { @@ -172,7 +172,7 @@ class ReportActivityMaterialController extends Controller ->join("m_req_material as m", "m.id", "=", "amta.material_id") ->join("m_users as u", "u.id", "=", "report_activity_material.user_id") ->where('report_activity_material.activity_id', $id_activity) - ->where('m.description', $materialName) + ->where('m.description', 'LIKE', '%' . $materialName . '%') ->orderBy('report_activity_material.report_date', 'asc') ->get(); if ($baselineDuration > 0) { From 8d33fbae3269afa3446f99896c4469b5fc311ad2 Mon Sep 17 00:00:00 2001 From: wahyu Date: Tue, 19 Dec 2023 11:52:46 +0700 Subject: [PATCH 040/155] update hierarchy progress --- app/Http/Controllers/VersionGanttController.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/app/Http/Controllers/VersionGanttController.php b/app/Http/Controllers/VersionGanttController.php index c5fabab..7dde377 100644 --- a/app/Http/Controllers/VersionGanttController.php +++ b/app/Http/Controllers/VersionGanttController.php @@ -117,11 +117,9 @@ class VersionGanttController extends Controller ->where('m_activity.parent_id', null) ->get(); foreach($progress as $item) { - if($item->persentase_progress){ $item->progress = $item->persentase_progress; $item->bobot = $item->bobot_planning; $item->save(); - } } } From 7901aa0833906ceb5dc5102ec29797788792b88f Mon Sep 17 00:00:00 2001 From: wahyu Date: Tue, 19 Dec 2023 13:34:21 +0700 Subject: [PATCH 041/155] add gantt name on behind task project --- app/Http/Controllers/ProjectController.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 62bd9ab..5b5f30f 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -602,16 +602,16 @@ class ProjectController extends Controller ->value('end_date'); if(isset($payload['till_date'])) { if (isset($payload['scurve'])) { - $overdueActivities = Activity::where('proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('m_activity.proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); } else { - $overdueActivities = Activity::where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); } } else { if (isset($payload['scurve'])) { - $overdueActivities = Activity::where('proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('m_activity.proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); } else { - $overdueActivities = Activity::where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); } } $result->overdueActivities = $overdueActivities; From 2d7c424f0fa5e32804d8f329e182d1120e69fa31 Mon Sep 17 00:00:00 2001 From: wahyu Date: Tue, 19 Dec 2023 17:45:13 +0700 Subject: [PATCH 042/155] update dashboard bod error --- app/Http/Controllers/DashboardBoDController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index deb8065..af68816 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -61,7 +61,7 @@ class DashboardBoDController extends Controller $totalExpenditure = $totalInvoice = $totalPaidInvoice = 0; // we can't use eloquent's sum() method because someone decided to use varchar as datatype in rencana_biaya field - $totalBudgets = Project::select(DB::raw('SUM(CAST("rencana_biaya" AS DOUBLE PRECISION))')) + $totalBudgets = Project::select(DB::raw("SUM(CAST(REPLACE(rencana_biaya, ',', '.') AS DOUBLE PRECISION))")) ->where('mulai_proyek', 'like', $year) /* ->orWhere('akhir_proyek', 'like', $year) */ ->pluck('sum') @@ -315,7 +315,7 @@ class DashboardBoDController extends Controller private function countTotalProjectValueInDivision($id, $year) { - return Project::select(DB::raw('SUM(CAST("rencana_biaya" AS DOUBLE PRECISION))')) + return Project::select(DB::raw("SUM(CAST(REPLACE(rencana_biaya, ',', '.') AS DOUBLE PRECISION))")) ->where('mulai_proyek', 'like', $year) /* ->orWhere('akhir_proyek', 'like', $year) */ ->where('divisi_id', $id) From adfeb117f62a4fbada2e00cac5737472246d50d7 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 20 Dec 2023 05:54:05 +0700 Subject: [PATCH 043/155] add endpoint & logic color chart --- .../Controllers/DashboardBoDController.php | 100 +++++++++++++++++- .../ProjectExpenditureController.php | 93 ++++++++++++++++ .../ProjectFinancialHealthController.php | 93 ++++++++++++++++ .../Controllers/ProjectInvoiceController.php | 93 ++++++++++++++++ .../ProjectScheduleHealthController.php | 93 ++++++++++++++++ app/Models/ProjectExpenditure.php | 17 +++ app/Models/ProjectFinancialHealth.php | 17 +++ app/Models/ProjectInvoice.php | 17 +++ app/Models/ProjectScheduleHealth.php | 17 +++ routes/web.php | 28 +++++ 10 files changed, 566 insertions(+), 2 deletions(-) create mode 100644 app/Http/Controllers/ProjectExpenditureController.php create mode 100644 app/Http/Controllers/ProjectFinancialHealthController.php create mode 100644 app/Http/Controllers/ProjectInvoiceController.php create mode 100644 app/Http/Controllers/ProjectScheduleHealthController.php create mode 100644 app/Models/ProjectExpenditure.php create mode 100644 app/Models/ProjectFinancialHealth.php create mode 100644 app/Models/ProjectInvoice.php create mode 100644 app/Models/ProjectScheduleHealth.php diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index 81c8830..d82a3e9 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -2,15 +2,19 @@ namespace App\Http\Controllers; -use App\Helpers\MasterFunctionsHelper; +use App\Models\User; use App\Models\Divisi; use App\Models\Project; use App\Models\ProjectPhase; -use App\Models\User; +use App\Models\ProjectExpenditure; use App\Models\UserToVersionGantt; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; +use App\Models\ProjectScheduleHealth; +use App\Helpers\MasterFunctionsHelper; +use App\Models\ProjectFinancialHealth; +use App\Models\ProjectInvoice; class DashboardBoDController extends Controller { @@ -110,6 +114,98 @@ class DashboardBoDController extends Controller ], 200); } + public function getDetailExpenditureColor($company_id) { + $query = ProjectExpenditure::where('company_id',$company_id)->get(); + $data = []; + foreach($query as $value) { + if($value['name'] === 'Total Budget') { + $data['total_budget'] = $value['color']; + } + if($value['name'] === 'Expenditure') { + $data['total_expenditure'] = $value['color']; + } + if($value['name'] === 'Invoice') { + $data['total_invoice'] = $value['color']; + } + if($value['name'] === 'Cash In') { + $data['total_paid_invoice'] = $value['color']; + } + } + return response()->json([ + 'data' => [ + 'total_budget' => $data['total_budget'] ?? '', + 'total_expenditure' => $data['total_expenditure'] ?? '', + 'total_invoice' => $data['total_invoice'] ?? '', + 'total_paid_invoice' => $data['total_paid_invoice'] ?? '', + ] + ], 200); + } + + public function getDetailFinancialHealthColor($company_id) { + $query = ProjectFinancialHealth::where('company_id',$company_id)->get(); + $data = []; + foreach($query as $value) { + if($value['name'] === 'Cost Overrun') { + $data['overrun'] = $value['color']; + } + if($value['name'] === 'Early Warning') { + $data['warning'] = $value['color']; + } + if($value['name'] === 'On Budget') { + $data['on-budget'] = $value['color']; + } + } + return response()->json([ + 'data' => [ + 'overrun' => $data['overrun'] ?? '', + 'warning' => $data['warning'] ?? '', + 'on-budget' => $data['on-budget'] ?? '', + ] + ], 200); + } + + public function getDetailScheduleHealthColor($company_id) { + $query = ProjectScheduleHealth::where('company_id',$company_id)->get(); + $data = []; + foreach($query as $value) { + if($value['name'] === 'Behind Schedule') { + $data['behind-schedule'] = $value['color']; + } + if($value['name'] === 'Early Warning') { + $data['warning'] = $value['color']; + } + if($value['name'] === 'On Schedule') { + $data['on-schedule'] = $value['color']; + } + } + return response()->json([ + 'data' => [ + 'behind-schedule' => $data['behind-schedule'] ?? '', + 'warning' => $data['warning'] ?? '', + 'on-schedule' => $data['on-schedule'] ?? '', + ] + ], 200); + } + + public function getDetailInvoiceColor($company_id) { + $query = ProjectInvoice::where('company_id',$company_id)->get(); + $data = []; + foreach($query as $value) { + if($value['name'] === 'Invoiced') { + $data['invoiced'] = $value['color']; + } + if($value['name'] === 'Cash In') { + $data['paid'] = $value['color']; + } + } + return response()->json([ + 'data' => [ + 'invoiced' => $data['invoiced'] ?? '', + 'paid' => $data['paid'] ?? '' + ] + ], 200); + } + // integrasi public function getInvoiceOutstanding($year = '%', $company_id, $all_project, $hierarchy) { diff --git a/app/Http/Controllers/ProjectExpenditureController.php b/app/Http/Controllers/ProjectExpenditureController.php new file mode 100644 index 0000000..43f379d --- /dev/null +++ b/app/Http/Controllers/ProjectExpenditureController.php @@ -0,0 +1,93 @@ +validate($request, [ + 'name' => 'required' + ]); + $data = $request->all(); + // Set Unique + $result = ProjectExpenditure::query() + ->where([ + ['company_id',$data['company_id']], + ['name', $data['name']] + ])->first(); + if($result) { + return response()->json(['status'=>'failed','message'=>'Name is already exists!','code'=> 500], 500); + die; + } + + $data['created_by'] = $this->currentName; + + if(!ProjectExpenditure::create($data)) + 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(!$id || (int) $id < 0 || $id=="") + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + if(!$result = ProjectExpenditure::find($id)) + return response()->json(['status'=>'failed','message'=>'Failed to get data!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 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); + + if(!$data = ProjectExpenditure::find($id)) + return response()->json(['status'=>'failed','message'=>'data project expenditure not found!','code'=>400], 400); + + if(!$data->update($request->all())) + return response()->json(['status'=>'failed','message'=>'data project expenditure failed updated!','code'=>400], 400); + + return response()->json(['status'=>'success','message'=>'Data berhasil disimpan!','code'=>200], 200); + } + + public function delete($id) + { + + if(!$data = ProjectExpenditure::find($id)) + return response()->json(['status'=>'failed','message'=>'data project expenditure not found!','code'=>400], 400); + + if(!$data->delete()) + return response()->json(['status'=>'failed','message'=>'Data gagal dihapus!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data berhasil dihapus!','code'=>200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_proyek_expenditure'); + $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 = ProjectExpenditure::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'failed get list project expenditure, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + + } +} diff --git a/app/Http/Controllers/ProjectFinancialHealthController.php b/app/Http/Controllers/ProjectFinancialHealthController.php new file mode 100644 index 0000000..7fcabd6 --- /dev/null +++ b/app/Http/Controllers/ProjectFinancialHealthController.php @@ -0,0 +1,93 @@ +validate($request, [ + 'name' => 'required' + ]); + $data = $request->all(); + // Set Unique + $result = ProjectFinancialHealth::query() + ->where([ + ['company_id',$data['company_id']], + ['name', $data['name']] + ])->first(); + if($result) { + return response()->json(['status'=>'failed','message'=>'Name is already exists!','code'=> 500], 500); + die; + } + + $data['created_by'] = $this->currentName; + + if(!ProjectFinancialHealth::create($data)) + 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(!$id || (int) $id < 0 || $id=="") + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + if(!$result = ProjectFinancialHealth::find($id)) + return response()->json(['status'=>'failed','message'=>'Failed to get data!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 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); + + if(!$data = ProjectFinancialHealth::find($id)) + return response()->json(['status'=>'failed','message'=>'data financial health not found!','code'=>400], 400); + + if(!$data->update($request->all())) + return response()->json(['status'=>'failed','message'=>'Data financial health failed updated!','code'=>400], 400); + + return response()->json(['status'=>'success','message'=>'Data berhasil disimpan!','code'=>200], 200); + } + + public function delete($id) + { + + if(!$data = ProjectFinancialHealth::find($id)) + return response()->json(['status'=>'failed','message'=>'data financial health not found!','code'=>400], 400); + + if(!$data->delete()) + return response()->json(['status'=>'failed','message'=>'Data gagal dihapus!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data berhasil dihapus!','code'=>200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_proyek_financial_health'); + $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 = ProjectFinancialHealth::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'failed get list financial health, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + + } +} diff --git a/app/Http/Controllers/ProjectInvoiceController.php b/app/Http/Controllers/ProjectInvoiceController.php new file mode 100644 index 0000000..12f9a6f --- /dev/null +++ b/app/Http/Controllers/ProjectInvoiceController.php @@ -0,0 +1,93 @@ +validate($request, [ + 'name' => 'required' + ]); + $data = $request->all(); + // Set Unique + $result = ProjectInvoice::query() + ->where([ + ['company_id',$data['company_id']], + ['name', $data['name']] + ])->first(); + if($result) { + return response()->json(['status'=>'failed','message'=>'Name is already exists!','code'=> 500], 500); + die; + } + + $data['created_by'] = $this->currentName; + + if(!ProjectInvoice::create($data)) + 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(!$id || (int) $id < 0 || $id=="") + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + if(!$result = ProjectInvoice::find($id)) + return response()->json(['status'=>'failed','message'=>'Failed to get data!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 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); + + if(!$data = ProjectInvoice::find($id)) + return response()->json(['status'=>'failed','message'=>'data project invoice not found!','code'=>400], 400); + + if(!$data->update($request->all())) + return response()->json(['status'=>'failed','message'=>'data project invoice failed updated!','code'=>400], 400); + + return response()->json(['status'=>'success','message'=>'Data berhasil disimpan!','code'=>200], 200); + } + + public function delete($id) + { + + if(!$data = ProjectInvoice::find($id)) + return response()->json(['status'=>'failed','message'=>'data project invoice not found!','code'=>400], 400); + + if(!$data->delete()) + return response()->json(['status'=>'failed','message'=>'Data gagal dihapus!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data berhasil dihapus!','code'=>200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_proyek_invoice'); + $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 = ProjectInvoice::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'failed get list project invoice, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + + } +} diff --git a/app/Http/Controllers/ProjectScheduleHealthController.php b/app/Http/Controllers/ProjectScheduleHealthController.php new file mode 100644 index 0000000..2bae0bd --- /dev/null +++ b/app/Http/Controllers/ProjectScheduleHealthController.php @@ -0,0 +1,93 @@ +validate($request, [ + 'name' => 'required' + ]); + $data = $request->all(); + // Set Unique + $result = ProjectScheduleHealth::query() + ->where([ + ['company_id',$data['company_id']], + ['name', $data['name']] + ])->first(); + if($result) { + return response()->json(['status'=>'failed','message'=>'Name is already exists!','code'=> 500], 500); + die; + } + + $data['created_by'] = $this->currentName; + + if(!ProjectScheduleHealth::create($data)) + 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(!$id || (int) $id < 0 || $id=="") + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + if(!$result = ProjectScheduleHealth::find($id)) + return response()->json(['status'=>'failed','message'=>'Failed to get data!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 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); + + if(!$data = ProjectScheduleHealth::find($id)) + return response()->json(['status'=>'failed','message'=>'data schedule health not found!','code'=>400], 400); + + if(!$data->update($request->all())) + return response()->json(['status'=>'failed','message'=>'data schedule health failed updated!','code'=>400], 400); + + return response()->json(['status'=>'success','message'=>'Data berhasil disimpan!','code'=>200], 200); + } + + public function delete($id) + { + + if(!$data = ProjectScheduleHealth::find($id)) + return response()->json(['status'=>'failed','message'=>'data schedule health not found!','code'=>400], 400); + + if(!$data->delete()) + return response()->json(['status'=>'failed','message'=>'Data gagal dihapus!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data berhasil dihapus!','code'=>200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_proyek_schedule_health'); + $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 = ProjectScheduleHealth::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'failed get list schedule health, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + + } +} diff --git a/app/Models/ProjectExpenditure.php b/app/Models/ProjectExpenditure.php new file mode 100644 index 0000000..2eb803d --- /dev/null +++ b/app/Models/ProjectExpenditure.php @@ -0,0 +1,17 @@ +group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/dashboard/get-total-project-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerDivision'); $router->get('/dashboard/get-total-project-value-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectValuePerDivision'); $router->get('/dashboard/get-detail-expenditure/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getDetailExpenditure'); + $router->get('/dashboard/get-detail-expenditure-color/{company_id}', 'DashboardBoDController@getDetailExpenditureColor'); + $router->get('/dashboard/get-detail-financial-health-color/{company_id}', 'DashboardBoDController@getDetailFinancialHealthColor'); + $router->get('/dashboard/get-detail-schedule-health-color/{company_id}', 'DashboardBoDController@getDetailScheduleHealthColor'); + $router->get('/dashboard/get-detail-invoice-color/{company_id}', 'DashboardBoDController@getDetailInvoiceColor'); $router->post('/role/search', 'RoleController@search'); $router->post('/role/add', 'RoleController@add'); @@ -139,6 +143,30 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->delete('/project-phase/delete/{id}', 'ProjectPhaseController@delete'); $router->get('/project-phase/list', 'ProjectPhaseController@list'); + $router->post('/project-expenditure/add', 'ProjectExpenditureController@add'); + $router->post('/project-expenditure/search', 'ProjectExpenditureController@search'); + $router->get('/project-expenditure/edit/{id}', 'ProjectExpenditureController@edit'); + $router->put('/project-expenditure/update/{id}', 'ProjectExpenditureController@update'); + $router->delete('/project-expenditure/delete/{id}', 'ProjectExpenditureController@delete'); + + $router->post('/project-financial-health/add', 'ProjectFinancialHealthController@add'); + $router->post('/project-financial-health/search', 'ProjectFinancialHealthController@search'); + $router->get('/project-financial-health/edit/{id}', 'ProjectFinancialHealthController@edit'); + $router->put('/project-financial-health/update/{id}', 'ProjectFinancialHealthController@update'); + $router->delete('/project-financial-health/delete/{id}', 'ProjectFinancialHealthController@delete'); + + $router->post('/project-schedule-health/add', 'ProjectScheduleHealthController@add'); + $router->post('/project-schedule-health/search', 'ProjectScheduleHealthController@search'); + $router->get('/project-schedule-health/edit/{id}', 'ProjectScheduleHealthController@edit'); + $router->put('/project-schedule-health/update/{id}', 'ProjectScheduleHealthController@update'); + $router->delete('/project-schedule-health/delete/{id}', 'ProjectScheduleHealthController@delete'); + + $router->post('/project-invoice/add', 'ProjectInvoiceController@add'); + $router->post('/project-invoice/search', 'ProjectInvoiceController@search'); + $router->get('/project-invoice/edit/{id}', 'ProjectInvoiceController@edit'); + $router->put('/project-invoice/update/{id}', 'ProjectInvoiceController@update'); + $router->delete('/project-invoice/delete/{id}', 'ProjectInvoiceController@delete'); + $router->post('/user-to-project/assign', 'UserProyekController@assignUserProyek'); $router->post('/request-material/add', 'RequestMaterialController@add'); From cd2101a108fd41420fffd5fb30312a10ce90c06e Mon Sep 17 00:00:00 2001 From: wahyu Date: Wed, 20 Dec 2023 13:36:03 +0700 Subject: [PATCH 044/155] update report activity --- app/Http/Controllers/ReportActivityMaterialController.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index d5fc160..44b228b 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers; use App\Helpers\MasterFunctionsHelper; use Illuminate\Http\Request; +use Illuminate\Support\Facades\DB; use App\Models\ReportActivityMaterial; use App\Models\Activity; use App\Models\AssignMaterial; @@ -132,6 +133,7 @@ class ReportActivityMaterialController extends Controller public function datatables(Request $request){ $id_activity = $request->query('idAct'); + $id_am = $request->query('idAmi'); $type = $request->query('type'); $materialName = $request->query('materialName'); if($type == 'plan'){ @@ -143,7 +145,7 @@ class ReportActivityMaterialController extends Controller $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) - ->where('m.description', 'LIKE', '%' . $materialName . '%') + ->where('assign_material_to_activity.id', $id_am) ->orderBy('assign_material_to_activity.id', 'asc') ->get(); if ($baselineDuration > 0) { @@ -172,7 +174,7 @@ class ReportActivityMaterialController extends Controller ->join("m_req_material as m", "m.id", "=", "amta.material_id") ->join("m_users as u", "u.id", "=", "report_activity_material.user_id") ->where('report_activity_material.activity_id', $id_activity) - ->where('m.description', 'LIKE', '%' . $materialName . '%') + ->where('report_activity_material.assign_material_id', $id_am) ->orderBy('report_activity_material.report_date', 'asc') ->get(); if ($baselineDuration > 0) { From c67d62003c2f0b36bbe60c282f31f330ee1d82c1 Mon Sep 17 00:00:00 2001 From: ibnu Date: Wed, 20 Dec 2023 15:21:14 +0700 Subject: [PATCH 045/155] update user-to-activity --- .../Controllers/UserToActivityController.php | 22 ++++++++++++++++--- routes/web.php | 2 +- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index b387c24..e491e22 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -158,7 +158,7 @@ class UserToActivityController extends Controller $dataBuilder = $this->setUpPayload($payload, 'assign_hr_to_activity'); $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; + // $countBuilder = $dataBuilder['count']; if (isset($join_column)) { $startDate = $join_column['start_date']; $endDate = $join_column['end_date']; @@ -187,8 +187,24 @@ class UserToActivityController extends Controller } $dataGet = $filteredData; } - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + // $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>count($dataGet)], 200); + } + + public function activityUser(Request $request){ + $payload = $request->all(); + $query = DB::table('m_activity as ma') + ->select('ahta.id', 'ma.id as activity_id', 'ma.proyek_id', 'ma.name as join_second_name', 'ma.start_date as join_second_start_date', + 'ma.end_date as join_second_end_date', 'ma.persentase_progress', 'mvg.name_version', 'mp.nama as nama_proyek', 'mp.type_proyek_id') + ->join('assign_hr_to_activity as ahta', 'ahta.activity_id', '=', 'ma.id') + ->join('m_version_gantt as mvg', 'mvg.id', '=', 'ma.version_gantt_id') + ->join('m_proyek as mp', 'mp.id', '=', 'ma.proyek_id') + ->where('ahta.user_id', $payload['user_id']) + ->where('ma.start_date', '<=', $payload['start_date']) + ->where('ma.end_date', '>=', $payload['end_date']) + ->get(); + + return response()->json(['status'=>'success','code'=>200,'data'=>$query, 'totalRecord'=>count($request->all())], 200); } public function list() diff --git a/routes/web.php b/routes/web.php index f82f295..9f6c0e4 100644 --- a/routes/web.php +++ b/routes/web.php @@ -198,7 +198,7 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->post('/user-to-activity/add-multiple', 'UserToActivityController@addMultiple'); $router->get('/user-to-activity/edit/{id}', 'UserToActivityController@edit'); $router->put('/user-to-activity/update/{id}', 'UserToActivityController@update'); - $router->post('/user-to-activity/search', 'UserToActivityController@search'); + $router->post('/user-to-activity/search', 'UserToActivityController@activityUser'); $router->post('/user-to-activity/search-analysis', 'UserToActivityController@searchAnalysis'); $router->post('/user-to-activity/list-filtered', 'UserToActivityController@listFiltered'); $router->delete('/user-to-activity/delete/{id}', 'UserToActivityController@delete'); From 907b660b5e7b53fc7b3dae01a22eeecee652df9b Mon Sep 17 00:00:00 2001 From: ibnu Date: Wed, 20 Dec 2023 16:56:45 +0700 Subject: [PATCH 046/155] update search activity for mobile --- .../Controllers/UserToActivityController.php | 16 +++++++++++++--- routes/web.php | 3 ++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index e491e22..9703946 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -193,18 +193,28 @@ class UserToActivityController extends Controller public function activityUser(Request $request){ $payload = $request->all(); - $query = DB::table('m_activity as ma') + $activity = DB::table('m_activity as ma') ->select('ahta.id', 'ma.id as activity_id', 'ma.proyek_id', 'ma.name as join_second_name', 'ma.start_date as join_second_start_date', 'ma.end_date as join_second_end_date', 'ma.persentase_progress', 'mvg.name_version', 'mp.nama as nama_proyek', 'mp.type_proyek_id') ->join('assign_hr_to_activity as ahta', 'ahta.activity_id', '=', 'ma.id') ->join('m_version_gantt as mvg', 'mvg.id', '=', 'ma.version_gantt_id') - ->join('m_proyek as mp', 'mp.id', '=', 'ma.proyek_id') + ->join('m_proyek as mp', 'mp.id', '=', 'ma.proyek_id') ->where('ahta.user_id', $payload['user_id']) ->where('ma.start_date', '<=', $payload['start_date']) ->where('ma.end_date', '>=', $payload['end_date']) ->get(); - return response()->json(['status'=>'success','code'=>200,'data'=>$query, 'totalRecord'=>count($request->all())], 200); + if ($payload['status'] != "") { + $filteredData = []; + foreach ($activity as $value) { + $assignMaterial = AssignMaterial::where('activity_id', $value->activity_id)->first(); + if ($assignMaterial->status_activity == $payload['status']) { + $filteredData[] = $value; + } + } + $activity = $filteredData; + } + return response()->json(['status'=>'success','code'=>200,'data'=>$activity, 'totalRecord'=>count($activity)], 200); } public function list() diff --git a/routes/web.php b/routes/web.php index 9f6c0e4..3938ef8 100644 --- a/routes/web.php +++ b/routes/web.php @@ -198,7 +198,8 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->post('/user-to-activity/add-multiple', 'UserToActivityController@addMultiple'); $router->get('/user-to-activity/edit/{id}', 'UserToActivityController@edit'); $router->put('/user-to-activity/update/{id}', 'UserToActivityController@update'); - $router->post('/user-to-activity/search', 'UserToActivityController@activityUser'); + $router->post('/user-to-activity/search', 'UserToActivityController@search'); + $router->post('/user-to-activity/by-date-status', 'UserToActivityController@activityUser'); $router->post('/user-to-activity/search-analysis', 'UserToActivityController@searchAnalysis'); $router->post('/user-to-activity/list-filtered', 'UserToActivityController@listFiltered'); $router->delete('/user-to-activity/delete/{id}', 'UserToActivityController@delete'); From a0f487fd328e07f5627a0d316f9b7e820a9cc730 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Thu, 21 Dec 2023 01:11:06 +0700 Subject: [PATCH 047/155] project charter --- app/Http/Controllers/ProjectController.php | 5 +++-- app/Models/Project.php | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 5b5f30f..104b128 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -53,7 +53,8 @@ class ProjectController extends Controller 'mulai_proyek' => 'required', 'akhir_proyek' => 'required', 'rencana_biaya' => 'required', - 'type_proyek_id' => 'required' + 'type_proyek_id' => 'required', + 'value_proyek' => 'required' ]); $data = $request->all(); @@ -543,7 +544,7 @@ class ProjectController extends Controller $maxEndDate = Activity::where('proyek_id', $id)->select('end_date') ->orderBy('end_date', 'desc') ->first(); - + }else{ // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') diff --git a/app/Models/Project.php b/app/Models/Project.php index cf2d0ad..2226419 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -25,6 +25,7 @@ class Project extends Model 'pm_id', 'type_proyek_id', 'divisi_id', + 'value_proyek', 'persentase_progress', 'keterangan', 'durasi_proyek', From 8b3bece9c08b8d24e205c5d03640a3f3bd0d479a Mon Sep 17 00:00:00 2001 From: wahyuun Date: Thu, 21 Dec 2023 11:53:50 +0700 Subject: [PATCH 048/155] add scoupe of work & fillable --- app/Http/Controllers/UserToProyekController.php | 3 ++- app/Models/Project.php | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/UserToProyekController.php b/app/Http/Controllers/UserToProyekController.php index f6fca59..a0606ea 100644 --- a/app/Http/Controllers/UserToProyekController.php +++ b/app/Http/Controllers/UserToProyekController.php @@ -50,7 +50,8 @@ class UserToProyekController extends Controller "user_id" => $item, "proyek_id" => $request->proyek_id, "created_by" => $this->currentName, - 'is_customer'=>true + 'is_customer'=>true, + 'project_role'=> $request->project_role ); $result = UserToProyek::create($dataInsert); diff --git a/app/Models/Project.php b/app/Models/Project.php index 2226419..1e575d6 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -23,6 +23,7 @@ class Project extends Model 'biaya_actual', 'company', 'pm_id', + 'scoupe_of_work', 'type_proyek_id', 'divisi_id', 'value_proyek', From d023856cb3980040efc2239eae057e4946d15ee4 Mon Sep 17 00:00:00 2001 From: ibnu Date: Thu, 21 Dec 2023 16:37:45 +0700 Subject: [PATCH 049/155] update where proyek_id --- app/Http/Controllers/UserToActivityController.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index 9703946..5a2238d 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -202,6 +202,7 @@ class UserToActivityController extends Controller ->where('ahta.user_id', $payload['user_id']) ->where('ma.start_date', '<=', $payload['start_date']) ->where('ma.end_date', '>=', $payload['end_date']) + ->where('ma.proyek', '>=', $payload['proyek_id']) ->get(); if ($payload['status'] != "") { From 8110897a3b1338de914ab14acd0ba32b59d23e40 Mon Sep 17 00:00:00 2001 From: ibnu Date: Thu, 21 Dec 2023 17:06:49 +0700 Subject: [PATCH 050/155] update add divisi name --- app/Http/Controllers/DashboardBoDController.php | 5 +++-- app/Models/Project.php | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index af68816..70bb309 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -350,8 +350,9 @@ class DashboardBoDController extends Controller public function getDetailExpenditure($year = '%') { $year = $this->interpolateYear($year); - $projects = Project::where('mulai_proyek', 'like', $year) - /* ->orWhere('akhir_proyek', 'like', $year) */ + $projects = Project::select('m_proyek.*', 'md.name as divisi_name') + ->where('mulai_proyek', 'like', $year) + ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') ->orderBy('id', 'desc') ->get(); foreach ($projects as $project) { diff --git a/app/Models/Project.php b/app/Models/Project.php index 1e575d6..2721944 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -15,6 +15,7 @@ class Project extends Model 'kode_sortname', 'jumlah_stakeholder', 'nama', + 'nickname', 'mulai_proyek', 'akhir_proyek', 'area_kerja', From 657095bfddef75b2ce8cada1798cac9f1f589e48 Mon Sep 17 00:00:00 2001 From: ibnu Date: Thu, 21 Dec 2023 17:50:45 +0700 Subject: [PATCH 051/155] add nickname add logic get data --- app/Http/Controllers/ProjectController.php | 30 +++++++++++++--------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 104b128..dd215ce 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -80,18 +80,24 @@ class ProjectController extends Controller if (empty($id) || !is_int((int)$id)) return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); - $result = Project::query() - ->from('m_proyek AS mp') - ->where('mp.id', $id) - ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); - - if (!is_null($result->first()['divisi_id'])) { - $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') - ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); - } - - $result = $result->first(); - + // $result = Project::query() + // ->from('m_proyek AS mp') + // ->where('mp.id', $id) + // ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek, + // area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); + + // if (!is_null($result->first()['divisi_id'])) { + // $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') + // ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); + // } + $result = Project::select('value_proyek','scoupe_of_work','kode_sortname','jumlah_stakeholder','nama','mulai_proyek','akhir_proyek', + 'area_kerja','rencana_biaya','biaya_actual','company','pm_id','type_proyek_id','divisi_id','persentase_progress', + 'keterangan','durasi_proyek','progress_by_worklog','currency_symbol','late_consequence','assumtion','currency_code', + 'currency_name','project_objectives','considered_success_when','potential_risk','testing_environment','budget_health', + 'phase_id','calculation_status','md.name as divisi_name', 'nickname') + ->join('m_divisi as md','md.id', '=', 'm_proyek.divisi_id') + ->where('m_proyek.id', $id) + ->first(); if(!$result) return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); From 59b170c7b9fb82a3744bab9e6ebc27f7f953d5bf Mon Sep 17 00:00:00 2001 From: ibnu Date: Thu, 21 Dec 2023 18:05:03 +0700 Subject: [PATCH 052/155] update user-activity --- app/Http/Controllers/UserToActivityController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index 5a2238d..c8a4f38 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -202,7 +202,7 @@ class UserToActivityController extends Controller ->where('ahta.user_id', $payload['user_id']) ->where('ma.start_date', '<=', $payload['start_date']) ->where('ma.end_date', '>=', $payload['end_date']) - ->where('ma.proyek', '>=', $payload['proyek_id']) + ->where('ma.proyek', $payload['proyek_id']) ->get(); if ($payload['status'] != "") { From d512aad318c5cc199f053cb73b2512866649018a Mon Sep 17 00:00:00 2001 From: ibnu Date: Thu, 21 Dec 2023 18:12:32 +0700 Subject: [PATCH 053/155] update user-activity --- app/Http/Controllers/UserToActivityController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index c8a4f38..bbd1b40 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -202,7 +202,7 @@ class UserToActivityController extends Controller ->where('ahta.user_id', $payload['user_id']) ->where('ma.start_date', '<=', $payload['start_date']) ->where('ma.end_date', '>=', $payload['end_date']) - ->where('ma.proyek', $payload['proyek_id']) + ->where('ma.proyek_id', $payload['proyek_id']) ->get(); if ($payload['status'] != "") { From 0ecacd65d8714f62f3792c811baff0423907de44 Mon Sep 17 00:00:00 2001 From: wahyu Date: Thu, 21 Dec 2023 20:41:10 +0700 Subject: [PATCH 054/155] use nickname --- app/Http/Controllers/DashboardBoDController.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index af68816..f07fff4 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -110,6 +110,7 @@ class DashboardBoDController extends Controller array_push($return, [ 'project' => $project->nama, 'project_code' => $project->kode_sortname, + 'nickname' => $project->nickname, 'invoiced' => $resp->data->total_invoice_amount ?? 0, 'paid' => $resp->data->total_invoice_paid_amount ?? 0, 'response' => $resp, From 20326961e36d5204f38f0594d92b29b877affbbd Mon Sep 17 00:00:00 2001 From: wahyu Date: Fri, 22 Dec 2023 11:07:02 +0700 Subject: [PATCH 055/155] fix open scurve error --- app/Http/Controllers/ProjectController.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 104b128..b4d963d 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -581,10 +581,12 @@ class ProjectController extends Controller $plannedEnd = Activity::where('version_gantt_id', $ganttId) ->orderByDesc('planned_end') ->value('planned_end'); - $result->header->start_date = $startDate; - $result->header->end_date = $maxEndDate->end_date; - $result->header->planned_start = $plannedStart; - $result->header->planned_end = $plannedEnd; + if (isset($result->header)) { + $result->header->start_date = $startDate; + $result->header->end_date = $maxEndDate->end_date; + $result->header->planned_start = $plannedStart; + $result->header->planned_end = $plannedEnd; + } return response()->json(['status'=>'success','code'=> 200,'data'=>$result, 'gantt'=>$ganttId], 200); } From c313683113ced3059af66fd37c335fff1770b93e Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 27 Dec 2023 10:18:29 +0700 Subject: [PATCH 056/155] add Hierarchy --- app/Http/Controllers/AuthController.php | 37 +- app/Http/Controllers/Controller.php | 2 +- app/Http/Controllers/ProjectController.php | 600 +++++++++++---------- app/Models/Project.php | 2 + 4 files changed, 351 insertions(+), 290 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index bb31e8c..37ae48f 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -11,6 +11,7 @@ use App\Models\Role; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Password; use Illuminate\Validation\ValidationException; + class AuthController extends Controller { public function __construct() @@ -25,46 +26,50 @@ class AuthController extends Controller $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); + if (empty($username) || empty($password)) + return response()->json(['status' => 'error', 'message' => 'You must fill all the fields'], 400); $usernameCheck = false; $passwordCheck = false; - - if (User::where('username', $username)->exists()) + + if (User::where('username', $username)->exists()) $usernameCheck = true; - if (User::where('password', md5($password))->exists()) + if (User::where('password', md5($password))->exists()) $passwordCheck = true; - if ($usernameCheck & $passwordCheck){ + if ($usernameCheck & $passwordCheck) { $user = User::where('username', $username)->where('password', md5($password))->first(); - if($is_mobile){ + if ($is_mobile) { $fcm_token = $request->fcm_token; - if(!$fcm_token || $fcm_token=="") - return response()->json(['status'=>'error','message'=>'FCM Token is required'], 400); + if (!$fcm_token || $fcm_token == "") + return response()->json(['status' => 'error', 'message' => 'FCM Token is required'], 400); $dataUpdateFcm = array( - "fcm_token"=>$fcm_token + "fcm_token" => $fcm_token ); $hr = User::find($user->id); - if($hr) + if ($hr) $hr->update($dataUpdateFcm); } $dataRole = Role::find($user->role_id); + $dataHierarchy = $this->getDataHierarchy($user->divisi_id, $user->id); - if($dataRole) + if ($dataRole) $user->role = $dataRole; - if (! $token =Auth::login($user)) + if ($dataHierarchy) + $user->hierarchy = $dataHierarchy; + + if (!$token = Auth::login($user)) return response()->json(['error' => 'Unauthorized'], 401); $ttl = 60; - if($remember) + if ($remember) $ttl = 10080; // todo : change existing md5 hashed function to laravel's originally bcrypt @@ -80,13 +85,13 @@ class AuthController extends Controller 'expires_in' => auth()->factory()->getTTL() * $ttl, ), ]); - }else { + } else { if (!$usernameCheck && !$passwordCheck) return response()->json(['code' => 201, 'message' => "username and password doesn't match"], 201); if (!$passwordCheck) return response()->json(['code' => 201, 'message' => "password doesn't match"], 201); if (!$usernameCheck) return response()->json(['code' => 201, 'message' => "username doesn't match"], 201); - } + } } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 02049ab..50966ce 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -7,8 +7,8 @@ use Illuminate\Support\Facades\Http; use App\Models\UserToActivity; use App\Models\Activity; use App\Models\AssignMaterial; -use App\Models\User; use App\Models\Divisi; +use App\Models\User; use Laravel\Lumen\Routing\Controller as BaseController; use App\Models\ReportK3Detail; diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index ca92810..ed9603e 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -50,7 +50,7 @@ class ProjectController extends Controller { $this->validate($request, [ 'nama' => 'required', - 'mulai_proyek' => 'required', + 'mulai_proyek' => 'required', 'akhir_proyek' => 'required', 'rencana_biaya' => 'required', 'type_proyek_id' => 'required' @@ -59,81 +59,82 @@ class ProjectController extends Controller $data = $request->all(); $data['created_by'] = $this->currentName; + $data['created_by_id'] = $this->currentId; - if(empty($data['phase_id'])) + if (empty($data['phase_id'])) $data['phase_id'] = 1; $result = Project::create($data); - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500], 500); + 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); + 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); + 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::query() - ->from('m_proyek AS mp') - ->where('mp.id', $id) - ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); + $result = Project::query() + ->from('m_proyek AS mp') + ->where('mp.id', $id) + ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); - if (!is_null($result->first()['divisi_id'])) { - $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') - ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); - } + if (!is_null($result->first()['divisi_id'])) { + $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') + ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); + } - $result = $result->first(); + $result = $result->first(); - if(!$result) - return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - return response()->json(['status'=>'success','code'=> 200,'data'=>$result], 200); + 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); + 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); + 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); + 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); + 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 + "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); @@ -145,15 +146,15 @@ class ProjectController extends Controller { $data = Project::find($id); - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + 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); + 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); + return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); } private function deleteRelative($project_id) @@ -168,12 +169,12 @@ class ProjectController extends Controller ProjectChecklists::where('proyek_id', $project_id)->delete(); ProjectIssues::where('proyek_id', $project_id)->delete(); ProjectRisks::where('proyek_id', $project_id)->delete(); - ProjectToChecklistK3::where('proyek_id', $project_id)->delete(); - HierarchyFtth::where('project_id', $project_id)->delete(); - AssignTools::where('proyek_id', $project_id)->delete(); - OfficeHours::where('proyek_id', $project_id)->delete(); - ReportK3::where('proyek_id', $project_id)->delete(); - RequestMaterial::where('proyek_id', $project_id)->delete(); + ProjectToChecklistK3::where('proyek_id', $project_id)->delete(); + HierarchyFtth::where('project_id', $project_id)->delete(); + AssignTools::where('proyek_id', $project_id)->delete(); + OfficeHours::where('proyek_id', $project_id)->delete(); + ReportK3::where('proyek_id', $project_id)->delete(); + RequestMaterial::where('proyek_id', $project_id)->delete(); $this->deleteVersionGantt($project_id); $this->deleteDokumenProject($project_id); } @@ -188,16 +189,16 @@ class ProjectController extends Controller 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); + 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); + if (file_exists($this->pathActivityDocument . $ad->file)) { + unlink($this->pathActivityDocument . $ad->file); } } ActivityDokumen::whereIn("activity_id", $activityIds)->delete(); @@ -215,8 +216,8 @@ class ProjectController extends Controller $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); + 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(); @@ -225,8 +226,8 @@ class ProjectController extends Controller $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); + if (file_exists($this->pathDocument . $dokumen->file)) { + unlink($this->pathDocument . $dokumen->file); } } @@ -240,11 +241,11 @@ class ProjectController extends Controller $dataBuilder = $this->setUpPayload($payload, 'm_proyek'); $builder = $dataBuilder['builder']; $countBuilder = $dataBuilder['count']; - // $builder->where("selfTable.created_by",$this->currentName); + // $builder->where("selfTable.created_by",$this->currentName); $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } public function list() @@ -286,101 +287,116 @@ class ProjectController extends Controller 'created_by', 'updated_at', 'updated_by' - )->orderBy('id', 'desc') - // ->where("created_by",$this->currentName) - ->get(); + )->orderBy('id', 'desc') + // ->where("created_by",$this->currentName) + ->get(); $countData = $data->count(); - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + if (!$data) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - $totalPlannedCost = array_sum(array_map('intval', array_column($data->toArray(), 'plannedCost'))); - $totalActualCost = $data->sum('actualCost'); + $totalPlannedCost = array_sum(array_map('intval', array_column($data->toArray(), 'plannedCost'))); + $totalActualCost = $data->sum('actualCost'); $manpowers = User::count(); $projectsOnDanger = Project::where('budget_health', 'overrun')->count(); - $projectPhases = ProjectPhase::orderBy('order', 'asc')->pluck('name'); - $projectTypes = ProjectType::orderBy('id', 'asc')->pluck('name'); - try { - $projectsByPhase = DB::table('m_proyek') - ->select('m_proyek_phase.name', 'm_proyek_phase.color', DB::raw('count(*) as total')) - ->join('m_proyek_phase', 'm_proyek_phase.id', '=', 'm_proyek.phase_id') - ->groupBy('m_proyek_phase.name', 'm_proyek_phase.color') - ->get(); - } catch (\Exception $e) { - return response()->json(['message' => $e->getMessage()]); - } - try { - $projectsByType = DB::table('m_proyek') - ->select('m_type_proyek.name', DB::raw('count(m_type_proyek.id) as total')) - ->join('m_type_proyek', 'm_type_proyek.id', '=', 'm_proyek.type_proyek_id') - ->groupBy('m_type_proyek.name') - ->get(); - } catch (\Exception $e) { - return response()->json(['message' => $e->getMessage()]); - } + $projectPhases = ProjectPhase::orderBy('order', 'asc')->pluck('name'); + $projectTypes = ProjectType::orderBy('id', 'asc')->pluck('name'); + try { + $projectsByPhase = DB::table('m_proyek') + ->select('m_proyek_phase.name', 'm_proyek_phase.color', DB::raw('count(*) as total')) + ->join('m_proyek_phase', 'm_proyek_phase.id', '=', 'm_proyek.phase_id') + ->groupBy('m_proyek_phase.name', 'm_proyek_phase.color') + ->get(); + } catch (\Exception $e) { + return response()->json(['message' => $e->getMessage()]); + } + try { + $projectsByType = DB::table('m_proyek') + ->select('m_type_proyek.name', DB::raw('count(m_type_proyek.id) as total')) + ->join('m_type_proyek', 'm_type_proyek.id', '=', 'm_proyek.type_proyek_id') + ->groupBy('m_type_proyek.name') + ->get(); + } catch (\Exception $e) { + return response()->json(['message' => $e->getMessage()]); + } return response()->json( - [ - 'status'=>'success', - 'code'=>200, - 'data'=>$data, - 'totalRecord'=>$countData, - 'totalPlannedCost' => $totalPlannedCost, - 'totalActualCost' => $totalActualCost, - 'totalRevenue' => $totalPlannedCost - $totalActualCost, - 'manpowers' => $manpowers, - 'projectsOnDanger'=> $projectsOnDanger, - 'projectPhases' => $projectPhases, - 'projectsByPhase' => $projectsByPhase, - 'projectTypes' => $projectTypes, - 'projectsByType' => $projectsByType, - ], 200); + [ + 'status' => 'success', + 'code' => 200, + 'data' => $data, + 'totalRecord' => $countData, + 'totalPlannedCost' => $totalPlannedCost, + 'totalActualCost' => $totalActualCost, + 'totalRevenue' => $totalPlannedCost - $totalActualCost, + 'manpowers' => $manpowers, + 'projectsOnDanger' => $projectsOnDanger, + 'projectPhases' => $projectPhases, + 'projectsByPhase' => $projectsByPhase, + 'projectTypes' => $projectTypes, + 'projectsByType' => $projectsByType, + ], + 200 + ); } - public function getListProjectTask($id){ - $data = UserToActivity::select("assign_hr_to_activity.user_id as user_id","m_proyek.*") + 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); + if (!$data) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - return response()->json(['status'=>'success','code'=>200,'data'=>$data], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } - public function getSCurve(Request $request){ + public function getSCurve(Request $request) + { $data = MasterFunctionsHelper::getSCurve($request); - return response()->json(['status'=>'success','code'=>200, 'data' => $data], 200); - } + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } - public function calculateSCurve(Request $request){ - $sCurve = Project::select('scurve')->where('id', $request->project_id)->first(); - return response()->json(['status'=>'success','code'=>200, 'data' => json_decode($sCurve->scurve)], 200); - } + // testing + public function calculateSCurvetest(Request $request) + { + $data = MasterFunctionsHelper::calculateSCurve($request->project_id); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } - public function sCurveCommand(Request $request){ - Artisan::call('calculate:scurve', [ - 'project_id' => $request->project_id - ]); - // $project = Project::find($request->project_id); + public function calculateSCurve(Request $request) + { + $sCurve = Project::select('scurve')->where('id', $request->project_id)->first(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => json_decode($sCurve->scurve)], 200); + } - // if ($project) { - // dispatch(new ProcessSCurve($project)); + public function sCurveCommand(Request $request) + { + Artisan::call('calculate:scurve', [ + 'project_id' => $request->project_id + ]); + // $project = Project::find($request->project_id); + + // if ($project) { + // dispatch(new ProcessSCurve($project)); - // return response()->json(['message' => 'S Curve calculation queued']); - // } + // return response()->json(['message' => 'S Curve calculation queued']); + // } - // return response()->json(['message' => 'Project not found'], 404); - } + // return response()->json(['message' => 'Project not found'], 404); + } - public function getLinearSCurve(Request $request){ + public function getLinearSCurve(Request $request) + { $data = MasterFunctionsHelper::getLinearSCurve($request); - return response()->json(['status'=>'success','code'=>200, 'data' => $data], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } - public static function setSyncDate($activity_id, $activity, $report) { + public static function setSyncDate($activity_id, $activity, $report) + { $status = AssignMaterial::where('activity_id', $activity_id)->first(); if (!isset($status)) { $reports = array( @@ -412,17 +428,17 @@ class ProjectController extends Controller return $reports; } - public function synchronizeReport($gantt_id) + public function synchronizeReport($gantt_id) { $activities = Activity::where("version_gantt_id", $gantt_id)->get(); $reports = []; - foreach($activities as $activity) { + foreach ($activities as $activity) { $activity_id = $activity->id; $countReports = ReportActivityMaterial::where('activity_id', $activity_id)->count(); if ($countReports === 1) { $dataReports = ReportActivityMaterial::where('activity_id', $activity_id)->orderBy('report_date')->get(); - foreach($dataReports as $dr) { + foreach ($dataReports as $dr) { $reports[] = ProjectController::setSyncDate($activity_id, $activity, $dr); } } @@ -443,15 +459,15 @@ class ProjectController extends Controller /* return response()->json(['status'=>'success','data'=> $reports,'code'=>200], 200); */ /* return response()->json(['status'=>'success','data'=> $activities,'code'=>200], 200); */ - for ($i=0; $i < count($reports); $i++) { + for ($i = 0; $i < count($reports); $i++) { $activity = Activity::find($reports[$i]['activity_id']); - if($reports[$i]['status'] != 'done'){ + if ($reports[$i]['status'] != 'done') { $reports[$i]['max_date']->modify('-1 day'); - }else if($reports[$i]['status'] == 'done'){ - $activity->actual_end = $reports[$i]['max_date']->setTime(23,59,59); + } else if ($reports[$i]['status'] == 'done') { + $activity->actual_end = $reports[$i]['max_date']->setTime(23, 59, 59); } $activity->start_date = $reports[$i]['min_date']; //same early - $activity->end_date = $reports[$i]['max_date']->setTime(23,59,59); // same early + $activity->end_date = $reports[$i]['max_date']->setTime(23, 59, 59); // same early $startDate = new DateTime($activity->start_date); $endDate = new DateTime($activity->end_date); $duration = MasterFunctionsHelper::countDays($activity->version_gantt_id, $startDate, $endDate); @@ -460,7 +476,7 @@ class ProjectController extends Controller $activity->save(); } - return response()->json(['status'=>'success','message'=>'Synchronize to report success!','code'=>200], 200); + return response()->json(['status' => 'success', 'message' => 'Synchronize to report success!', 'code' => 200], 200); } public function setBaseline($gantt_id) @@ -469,127 +485,139 @@ class ProjectController extends Controller foreach ($activities as $activity) { $activity->update([ - "planned_start"=>$activity->start_date, - "planned_end"=>$activity->end_date, - "early_start"=>$activity->start_date, - "early_end"=>$activity->end_date, + "planned_start" => $activity->start_date, + "planned_end" => $activity->end_date, + "early_start" => $activity->start_date, + "early_end" => $activity->end_date, ]); } - return response()->json(['status'=>'success','message'=>'Set baseline success!','code'=> 200], 200); + return response()->json(['status' => 'success', 'message' => 'Set baseline success!', 'code' => 200], 200); } - public function getInvoiceIntegration(Request $request) { - $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); + public function getInvoiceIntegration(Request $request) + { + $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); $search = urlencode($request->search); - if(empty($search)) - return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw').'/project_cost?project_no=SEARCH'); + if (empty($search)) + return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); + $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); $response = MasterFunctionsHelper::curlReq($url); - if (isset($request->gantt_id)) { - $response->data->total_cost = $response->data->total_cost / $ganttCount; - } + if (isset($request->gantt_id)) { + $response->data->total_cost = $response->data->total_cost / $ganttCount; + } + + return response()->json(['status' => 'success', 'data' => $response, 'code' => 200], 200); + } + public function getByUser($id) + { + $alias = "utp"; + $userProyek = UserToProyek::query() + ->from('assign_hr_to_proyek AS ' . $alias) + ->where([ + ['is_customer', true], + ['user_id', $id] + ]) + ->leftJoin('m_users', $alias . '.user_id', '=', 'm_users.id') + ->leftJoin('m_proyek', $alias . '.proyek_id', '=', 'm_proyek.id') + ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') + ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name', 'm_users.name AS join_first_name') + ->get(); + $totalRecord = $userProyek->count(); - return response()->json(['status'=>'success', 'data'=> $response, 'code'=>200], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); } - public function getByUser($id) - { - $alias = "utp"; - $userProyek = UserToProyek::query() - ->from('assign_hr_to_proyek AS ' . $alias) - ->where([ - ['is_customer', true], - ['user_id', $id] - ]) - ->leftJoin('m_users', $alias.'.user_id', '=', 'm_users.id') - ->leftJoin('m_proyek', $alias.'.proyek_id', '=', 'm_proyek.id') - ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') - ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name','m_users.name AS join_first_name') - ->get(); - $totalRecord = $userProyek->count(); - - return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); - } - public function detail(Request $request, $id, $gantt_id = null, $s_curve = null){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + public function detail(Request $request, $id, $gantt_id = null, $s_curve = null) + { + 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); - if (!isset($gantt_id)) { - $gantt = MasterFunctionsHelper::getLatestGantt($id); - $ganttId = $gantt['last_gantt_id']; - } else { - $ganttId = $gantt_id; - } + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + if (!isset($gantt_id)) { + $gantt = MasterFunctionsHelper::getLatestGantt($id); + $ganttId = $gantt['last_gantt_id']; + } else { + $ganttId = $gantt_id; + } $result->projectManager = User::where('id', $result->pm_id)->value('name'); - if (isset($s_curve)) { - $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->first(); - $actualStartExist = Activity::where('proyek_id', $id)->whereNotNull('actual_start')->exists(); - if($result['type_proyek_id'] === 9) - { - $actualEndExist = Activity::where('proyek_id', $id)->exists(); - $query = Activity::where('proyek_id', $id); - }else{ - $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); - $query = Activity::where('version_gantt_id', $ganttId); - } - } else { - $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $ganttId)->first(); - $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); - $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); - $query = Activity::where('version_gantt_id', $ganttId); - } - - if ($actualStartExist) { - $startDate = $query->orderBy('actual_start')->value('start_date'); - } else { - $startDate = $query->orderBy('start_date')->value('start_date'); - } - if($actualEndExist) - { - $maxEndDate = $query->max('id'); - $endDate = $query->where('id',$maxEndDate)->first()->end_date; - } - - $plannedStart = Activity::where('version_gantt_id', $ganttId) - ->orderBy('planned_start') - ->value('planned_start'); - $plannedEnd = Activity::where('version_gantt_id', $ganttId) - ->orderByDesc('planned_end') - ->value('planned_end'); - $result->header->start_date = $startDate; - $result->header->end_date = $endDate; - $result->header->planned_start = $plannedStart; - $result->header->planned_end = $plannedEnd; - return response()->json(['status'=>'success','code'=> 200,'data'=>$result, 'gantt'=>$ganttId], 200); + if (isset($s_curve)) { + $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->first(); + $actualStartExist = Activity::where('proyek_id', $id)->whereNotNull('actual_start')->exists(); + if ($result['type_proyek_id'] === 9) { + // $actualEndExist = Activity::where('proyek_id', $id)->exists(); + $query = Activity::where('proyek_id', $id); + $maxEndDate = Activity::where('proyek_id', $id)->select('end_date') + ->orderBy('end_date', 'desc') + ->first(); + } else { + // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') + ->orderBy('end_date', 'desc') + ->first(); + $query = Activity::where('version_gantt_id', $ganttId); + } + } else { + $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $ganttId)->first(); + $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); + // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') + ->orderBy('end_date', 'desc') + ->first(); + $query = Activity::where('version_gantt_id', $ganttId); + } + + if ($actualStartExist) { + $startDate = $query->orderBy('actual_start')->value('start_date'); + } else { + $startDate = $query->orderBy('start_date')->value('start_date'); + } + // if($actualEndExist) + // { + // // $maxEndDate = $query->max('id'); + // // get last end_date + // // $endDate = $query->where('id',$maxEndDate)->first()->end_date; + + // } + + $plannedStart = Activity::where('version_gantt_id', $ganttId) + ->orderBy('planned_start') + ->value('planned_start'); + $plannedEnd = Activity::where('version_gantt_id', $ganttId) + ->orderByDesc('planned_end') + ->value('planned_end'); + $result->header->start_date = $startDate; + $result->header->end_date = $maxEndDate->end_date; + $result->header->planned_start = $plannedStart; + $result->header->planned_end = $plannedEnd; + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result, 'gantt' => $ganttId], 200); } - public function getOverdueActivities(Request $request){ + public function getOverdueActivities(Request $request) + { $payload = $request->all(); - if(empty($payload['id']) || !is_int((int)$payload['id'])) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + if (empty($payload['id']) || !is_int((int)$payload['id'])) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); $result = Project::find($payload['id']); - if(!$result) - return response()->json(['status'=>'failed','message'=> 'Project not found!','code'=> 404], 404); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Project not found!', 'code' => 404], 404); //TODO possible overdue bug $endDate = Activity::where('proyek_id', $payload['id']) ->orderByDesc('end_date') ->value('end_date'); - if(isset($payload['till_date'])) { + if (isset($payload['till_date'])) { if (isset($payload['scurve'])) { - $overdueActivities = Activity::where('proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('m_activity.proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); } else { - $overdueActivities = Activity::where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date','<=',$endDate)->orderBy('end_date', 'asc')->get(); + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); } - } - else { + } else { if (isset($payload['scurve'])) { $overdueActivities = Activity::where('proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); } else { @@ -598,53 +626,75 @@ class ProjectController extends Controller } $result->overdueActivities = $overdueActivities; - return response()->json(['status'=>'success','code'=> 200,'data'=>$result], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); } - public function getReportDistribution(Request $request){ + public function getReportDistribution(Request $request) + { $payload = $request->all(); - if(empty($payload['project_id']) || !is_int((int)$payload['project_id'])) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + if (empty($payload['project_id']) || !is_int((int)$payload['project_id'])) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); $reports = DB::table('assign_material_to_activity as ama') - ->select('u.name', 'a.name as activity_name', 'ama.qty_planning', 'ram.qty as qty_real','rm.description as material_name', 'rm.uom as material_unit', - 'ram.lat', 'ram.lon', 'ram.description as report_notes', 'ram.report_date') + ->select( + 'u.name', + 'a.name as activity_name', + 'ama.qty_planning', + 'ram.qty as qty_real', + 'rm.description as material_name', + 'rm.uom as material_unit', + 'ram.lat', + 'ram.lon', + 'ram.description as report_notes', + 'ram.report_date' + ) ->join('report_activity_material as ram', 'ram.assign_material_id', '=', 'ama.id') ->join('m_req_material as rm', 'rm.id', '=', 'ama.material_id') ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') ->join('m_users as u', 'u.id', '=', 'ram.user_id') ->where('ama.proyek_id', '=', $payload['project_id']) ->whereNotNull('ram.lat') - ->whereBetween('ram.report_date', [$payload['start_date'], $payload['end_date']]); + ->whereBetween('ram.report_date', [$payload['start_date'], $payload['end_date']]); - return response()->json(['status'=>'success', 'code'=> 200, 'data'=> $reports], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $reports], 200); } - public function getManpower($proyek_id){ + public function getManpower($proyek_id) + { $manCount = UserToProyek::where('proyek_id', $proyek_id)->count(); - return response()->json(['totalRecord'=>$manCount]); + return response()->json(['totalRecord' => $manCount]); } - public function getAssignedHR($gantt_id){ + public function getAssignedHR($gantt_id) + { $results = UserToActivity::select('assign_hr_to_activity.proyek_id', 'assign_hr_to_activity.user_id', 'm_activity.id', 'm_activity.name', 'm_activity.start_date', 'm_activity.end_date') ->join('m_activity', 'm_activity.id', '=', 'assign_hr_to_activity.activity_id') ->where('assign_hr_to_activity.version_gantt_id', $gantt_id) ->get(); - return response()->json(['data'=>$results]); + return response()->json(['data' => $results]); } public function dashboard($id) { $data = DB::table('m_proyek as mp') - ->select('mp.kode_sortname', 'mp.nama as name_project', 'mp.mulai_proyek as start', 'mp.akhir_proyek as finish', - 'mp.rencana_biaya', 'mp.company', 'mp.currency_symbol', 'mu.name as pm', 'mp.budget_health') - ->join('m_users as mu', 'mu.id', '=', 'mp.pm_id') - ->where('mp.id', $id) - ->first(); - - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data tidak ditemukan!','code'=> 404], 404); + ->select( + 'mp.kode_sortname', + 'mp.nama as name_project', + 'mp.mulai_proyek as start', + 'mp.akhir_proyek as finish', + 'mp.rencana_biaya', + 'mp.company', + 'mp.currency_symbol', + 'mu.name as pm', + 'mp.budget_health' + ) + ->join('m_users as mu', 'mu.id', '=', 'mp.pm_id') + ->where('mp.id', $id) + ->first(); + + if (!$data) + return response()->json(['status' => 'failed', 'message' => 'Data tidak ditemukan!', 'code' => 404], 404); $manpowers = UserToProyek::where('proyek_id', $id)->count(); $rootActivity = Activity::whereNull('parent_id')->where('proyek_id', $id)->orderBy('version_gantt_id', 'desc')->first(); @@ -653,38 +703,42 @@ class ProjectController extends Controller $progress = @$rootActivity->persentase_progress ?? 0; $commentActivity = DB::table('m_comment_activity as mca') - ->select('mca.activity_id', 'mca.comment as comment', 'mca.created_by as comment_by', 'mca.created_at as comment_created', - 'ma.name as activity') - ->join('m_activity as ma', 'ma.id', '=', 'mca.activity_id') - ->where('ma.proyek_id', $id) - ->orderBy('comment_by') - ->take(2) - ->get(); + ->select( + 'mca.activity_id', + 'mca.comment as comment', + 'mca.created_by as comment_by', + 'mca.created_at as comment_created', + 'ma.name as activity' + ) + ->join('m_activity as ma', 'ma.id', '=', 'mca.activity_id') + ->where('ma.proyek_id', $id) + ->orderBy('comment_by') + ->take(2) + ->get(); $data->actual_cost = $actualCost; $data->progress = $progress; $data->comment = $commentActivity; $data->man_power = $manpowers; - return response()->json(['status'=>'success','code'=>200,'data'=> $data], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } - private function httpReq($search){ - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, str_replace("ADDR", $search, API_GEOLOCATION)); + private function httpReq($search) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, str_replace("ADDR", $search, API_GEOLOCATION)); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); $info = curl_getinfo($ch); - $output = curl_exec($ch); - curl_close($ch); + $output = curl_exec($ch); + curl_close($ch); - return json_decode($output); + return json_decode($output); } - } - diff --git a/app/Models/Project.php b/app/Models/Project.php index 115c9b6..5ac9382 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -23,8 +23,10 @@ class Project extends Model 'biaya_actual', 'company', 'pm_id', + 'scoupe_of_work', 'type_proyek_id', 'divisi_id', + 'value_proyek', 'persentase_progress', 'keterangan', 'durasi_proyek', From 11cda6e40cf4efcf04fa33bc157757006634ce8f Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 27 Dec 2023 10:18:45 +0700 Subject: [PATCH 057/155] update early warning to 20% --- .../Controllers/DashboardBoDController.php | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index deb8065..65f6a39 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -41,14 +41,14 @@ class DashboardBoDController extends Controller private function getInvoiceIntegration($search) { - if(empty($search)) - return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); + if (empty($search)) + return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw').'/project_cost?project_no=SEARCH'); + $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); $token = config('api.adw_token'); $response = $this->curlReq($url, $token); - if(@$response->data->project_no == "") + if (@$response->data->project_no == "") return null; return $response; @@ -83,7 +83,6 @@ class DashboardBoDController extends Controller $totalInvoice += $resp->data->total_invoice_amount ?? 0; $totalPaidInvoice += $resp->data->total_invoice_paid_amount ?? 0; } - } return response()->json([ @@ -147,15 +146,13 @@ class DashboardBoDController extends Controller } $selisihProgress = $planningProgress - $actualProgress; try { - if ($selisihProgress > 0 && $selisihProgress <= 5){ + if ($selisihProgress > 0 && $selisihProgress <= 20) { $return['warning'] += 1; $projects[$index]->status = 'warning'; - } - elseif ($selisihProgress == 0){ + } elseif ($selisihProgress == 0) { $return['on-schedule'] += 1; $projects[$index]->status = 'on-schedule'; - } - else { + } else { $return['behind-schedule'] += 1; $projects[$index]->status = 'behind-schedule'; } @@ -191,13 +188,11 @@ class DashboardBoDController extends Controller $actualProgress = !empty($actualArray) ? $actualArray[count($actualArray) - 1] : 0; } $selisihProgress = $planningProgress - $actualProgress; - if ($selisihProgress > 0 && $selisihProgress <= 5){ + if ($selisihProgress > 0 && $selisihProgress <= 5) { $warning++; - } - elseif ($selisihProgress == 0){ + } elseif ($selisihProgress == 0) { $onSchedule++; - } - else { + } else { $behindSchedule++; } } @@ -294,7 +289,7 @@ class DashboardBoDController extends Controller { $year = $this->interpolateYear($year); - $divisions = Divisi::select('id', 'name','parent','color') + $divisions = Divisi::select('id', 'name', 'parent', 'color') ->with('children') ->whereNull('parent') ->get(); From d87899eddad4c84c02a9a180a86f0a8c6af5a15a Mon Sep 17 00:00:00 2001 From: wahyu Date: Wed, 27 Dec 2023 10:49:59 +0700 Subject: [PATCH 058/155] scurve daily --- app/Helpers/MasterFunctionsHelper.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index b2ff5f7..be83cf1 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -556,7 +556,6 @@ class MasterFunctionsHelper // if (new \DateTime($loopDay) < $today) { // $statusCutOfDate = true; // } - if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); if (new \DateTime($loopDay . ' Friday') <= new \DateTime($today . ' Friday')) { @@ -564,7 +563,6 @@ class MasterFunctionsHelper $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); } $dateWeek[] = [$loopDay]; - } // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; foreach ($dataPlanM as $keyPlanM) { # hitung untuk persentase progress planning @@ -1436,7 +1434,6 @@ class MasterFunctionsHelper $dataActivityPlan = []; $dataActivityActual = []; $today = date('Y-m-d'); - if (new \DateTime($loopDay) == new \DateTime($loopDay . ' Friday')){ $progressPlanKomulatifWeek[] += round($tmpProgressPlanWeek,2); if (new \DateTime($loopDay . ' Friday') <= new \DateTime($today . ' Friday')) { @@ -1444,7 +1441,6 @@ class MasterFunctionsHelper $progressActualKomulatifWeek[] += round($tmpProgressActualWeek,2); } $dateWeek[] = [$loopDay]; - } // $progressPlanKomulatifWeek[] += $tmpProgressPlanWeek; // if (count($dataPlanM) > 0 && count($dataPlanM[0]) > 0) { foreach ($dataPlanM as $keyPlanM) { From b44644f13abca7dbd80ab722098f4442c832badc Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 27 Dec 2023 10:57:53 +0700 Subject: [PATCH 059/155] update type condition --- app/Http/Controllers/ActivityController.php | 255 ++++++++++---------- 1 file changed, 128 insertions(+), 127 deletions(-) diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index cbb425e..a9a56e4 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -1,4 +1,5 @@ json(['status' => 'success', 'data' => $dataGantt, 'code' => 200], 200); } - public function activitySCurve($proyek_id, $gantt_id){ - - // "data": [ - // { - // "id": 1, - // "text": "Office itinerancy", - // "type": "project", - // "order": "10", - // "progress": 0.4, - // "open": true, - // "user":"0", - // "start_date": "02-04-2024 00:00", - // "duration": 17, - // "end_date": "19-04-2024 00:00", - // "parent": 0 - // } - // ], - // "links": [ - // { - // "id": "1", - // "source": "1", - // "target": "2", - // "type": "1" - // } - // ] - // } + public function activitySCurve($proyek_id, $gantt_id) + { + + // "data": [ + // { + // "id": 1, + // "text": "Office itinerancy", + // "type": "project", + // "order": "10", + // "progress": 0.4, + // "open": true, + // "user":"0", + // "start_date": "02-04-2024 00:00", + // "duration": 17, + // "end_date": "19-04-2024 00:00", + // "parent": 0 + // } + // ], + // "links": [ + // { + // "id": "1", + // "source": "1", + // "target": "2", + // "type": "1" + // } + // ] + // } $checkHeader = Activity::where('version_gantt_id', $gantt_id)->where('type_activity', 'header')->count(); $finalData = []; if ($checkHeader > 0) { $dataHeader = Activity::select('id', 'name as text', 'type_activity as type', 'persentase_progress as progress', 'start_date', 'end_date', 'duration', 'parent_id', 'sortorder as order')->where('version_gantt_id', $gantt_id)->where('type_activity', 'header')->first(); - + // $dataHeader->start_date1 = isset($dataHeader->start) ? date_format(date_create($dataHeader->start), "d-m-Y H:i") : NULL; // $dataHeader->end_date1 = isset($dataHeader->end) ? date_format(date_create($dataHeader->end), "d-m-Y H:i") : NULL; - + $dataHeader->progress = $dataHeader->progress / 100; - + $dataHeader->type = "project"; $dataHeader->text = $dataHeader->name; $finalData[] = $dataHeader; @@ -84,17 +86,17 @@ class ActivityController extends Controller foreach ($data as $objRow) { $type = "project"; - $dataChildren = $this->getChildrenSCurve($gantt_id, $objRow->id); + $dataChildren = $this->getChildrenSCurve($gantt_id, $objRow->id); if ($objRow->type_activity == "milestone") $type = $objRow->type_activity; if (empty($dataChildren)) $type = "task"; - - $objRow->parent = $objRow->parent_id ? $objRow->parent_id : null; + + $objRow->parent = $objRow->parent_id ? $objRow->parent_id : null; // $objRow->start_date = isset($objRow->start) ? date_format(date_create($objRow->start), "d-m-Y H:i") : NULL; // $objRow->end_date1 = isset($objRow->end) ? date_format(date_create($objRow->end), "d-m-Y H:i") : NULL; - + $objRow->progress = $objRow->persentase_progress / 100; $objRow->type = $type; $finalData[] = $objRow; @@ -120,9 +122,8 @@ class ActivityController extends Controller "data" => $finalData, "links" => $finalLink ); - - return response()->json(['status' => 'success', 'data' => $resultData, 'code' => 200], 200); + return response()->json(['status' => 'success', 'data' => $resultData, 'code' => 200], 200); } private function getDataActivity($id) @@ -207,15 +208,15 @@ class ActivityController extends Controller private function getChildrenSCurve($gantt_id, $parent_id) { $finalData = []; - + $data = Activity::select('id', 'name as text', 'type_activity as type', 'bobot_planning', 'persentase_progress as progress', 'start_date', 'end_date', 'duration', 'parent_id', 'sortorder as order') - ->where('version_gantt_id', $gantt_id)->where('parent_id', $parent_id)->orderBy('sortorder', 'asc')->get(); + ->where('version_gantt_id', $gantt_id)->where('parent_id', $parent_id)->orderBy('sortorder', 'asc')->get(); foreach ($data as $objRow) { - $objRow->parent = $parent_id; - $objRow->progress = (float) $objRow->bobot_planning /100; + $objRow->parent = $parent_id; + $objRow->progress = (float) $objRow->bobot_planning / 100; // $objRow->start_date1 = isset($objRow->start) ? date_format(date_create($objRow->start), "d-m-Y H:i") : NULL; // $objRow->end_date1 = isset($objRow->end) ? date_format(date_create($objRow->end), "d-m-Y H:i") : NULL; - + $dataChildren = $this->getChildrenSCurve($gantt_id, $objRow->id); if ($objRow->type_activity == "milestone") { $objRow->type = $objRow->type_activity; @@ -234,7 +235,7 @@ class ActivityController extends Controller // $actualEnd = $this->getFirstLastDateActivity($objRow->id, "end"); // $objRow->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "d-m-Y") : NULL; - } + } $finalData[] = $objRow; $finalData = array_merge($finalData, $dataChildren); } @@ -264,7 +265,7 @@ class ActivityController extends Controller $objRow->type = "task"; $objRow->actual_start = isset($objRow->actual_start) ? date_format(date_create($objRow->actual_start), "Y-m-d") : NULL; $objRow->actual_end = isset($objRow->actual_end) ? date_format(date_create($objRow->actual_end), "Y-m-d") : NULL; - if(isset($objRow->actual_start)){ + if (isset($objRow->actual_start)) { $objRow->auto_scheduling = false; } } else { @@ -281,66 +282,67 @@ class ActivityController extends Controller return $finalData; } - public function getActivityFirst($parentId){ + public function getActivityFirst($parentId) + { $activity = Activity::where('parent_id', $parentId)->orderByRaw('actual_start ASC')->first(); if (!isset($activity)) { return null; } - if($activity->type_activity == "task"){ + if ($activity->type_activity == "task") { // Log::info("activity ", [$activity]); return $activity->actual_start; - }else{ + } else { return $this->getActivityFirst($activity->id); } - } - public function getFirstLastDateActivity($id, $params){ - if($params == "start"){ + public function getFirstLastDateActivity($id, $params) + { + if ($params == "start") { $data = Activity::select('id', 'parent_id', 'name', 'actual_start')->where('parent_id', $id)->get(); - }else{ + } else { $data = Activity::select('id', 'parent_id', 'name', 'actual_end')->where('parent_id', $id)->get(); } - $parent = Activity::findOrFail($id); - $dataFinal=[]; + $parent = Activity::findOrFail($id); + $dataFinal = []; foreach ($data as $val) { $activity = $this->getchildActivityForActual($val->id, $params); $dataFinal[] = $val; $dataFinal = array_merge($dataFinal, $activity); - } - if($params == "start"){ - $actualStartValues = array_column(array_filter($dataFinal, function($item) { + if ($params == "start") { + $actualStartValues = array_column(array_filter($dataFinal, function ($item) { return isset($item['actual_start']); }), 'actual_start'); $returnActualStartOrEnd = count($actualStartValues) > 0 ? min($actualStartValues) : null; - if (isset($parent)) { - $parent->actual_start = $returnActualStartOrEnd; - $parent->save(); - } - }else{ - $actualEndValues = array_column(array_filter($dataFinal, function($item) { + if (isset($parent)) { + $parent->actual_start = $returnActualStartOrEnd; + $parent->save(); + } + } else { + $actualEndValues = array_column(array_filter($dataFinal, function ($item) { return isset($item['actual_end']); }), 'actual_end'); $returnActualStartOrEnd = count($actualEndValues) == count($dataFinal) && count($actualEndValues) > 0 ? max($actualEndValues) : null; - if (isset($parent)) { - $parent->actual_end = $returnActualStartOrEnd; - $parent->save(); - } + if (isset($parent)) { + $parent->actual_end = $returnActualStartOrEnd; + $parent->save(); + } } // return json_encode(["min"=>$minActualStart, "max"=>$maxActualStart]); return $returnActualStartOrEnd; } - public function getchildActivityForActual($parent, $params){ - if($params == "start"){ + public function getchildActivityForActual($parent, $params) + { + if ($params == "start") { $activity = Activity::select('id', 'actual_start')->where('parent_id', $parent)->get(); - }else{ + } else { $activity = Activity::select('id', 'actual_end')->where('parent_id', $parent)->get(); } $temp = []; - foreach($activity as $val1){ + foreach ($activity as $val1) { $getChild = $this->getchildActivityForActual($val1->id, $params); $temp[] = $val1; $temp = array_merge($temp, $getChild); @@ -348,18 +350,18 @@ class ActivityController extends Controller return $temp; } - public function getActivityLast($parentId){ + public function getActivityLast($parentId) + { $activity = Activity::where('parent_id', $parentId)->orderByRaw('actual_end DESC')->first(); if (!isset($activity)) { return null; } - if($activity->type_activity == "task"){ + if ($activity->type_activity == "task") { // Log::info("activity ", [$activity]); return $activity->actual_end; - }else{ + } else { return $this->getActivityLast($activity->id); } - } private function cloneTemplate($id, $proyek_id, $hierarchy_ftth_id = null) @@ -547,53 +549,54 @@ class ActivityController extends Controller return response()->json(['status' => 'success', 'message' => 'Activity Updated!', 'code' => 200], 200); } - public function updateSchedule($ganttId){ - if (empty($ganttId) || !is_int((int) $ganttId)) + public function updateSchedule($ganttId) + { + if (empty($ganttId) || !is_int((int) $ganttId)) return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); - $activities = Activity::where('version_gantt_id', $ganttId)->get(); + $activities = Activity::where('version_gantt_id', $ganttId)->get(); if (!$activities) return response()->json(['status' => 'failed', 'message' => 'Activities not found!', 'code' => 404], 404); $duration = 0; - foreach ($activities as $key => $activity) { - $assignMaterial = AssignMaterial::where('activity_id', $activity->id)->first(); + foreach ($activities as $key => $activity) { + $assignMaterial = AssignMaterial::where('activity_id', $activity->id)->first(); if (isset($assignMaterial)) { $statusActivity = $assignMaterial->status_activity; } else { $statusActivity = ''; } - if (isset($activity->planned_start) && isset($activity->planned_end) && $statusActivity != "done") { - // todo check report for no report / progress == 0 - $today = new DateTime(); - $endDate = new DateTime($activity->end_date); - $startDate = new DateTime($activity->start_date); - $plannedStart = new DateTime($activity->planned_start); - $plannedEnd = new DateTime($activity->planned_end); - $duration = MasterFunctionsHelper::countDays($ganttId, $plannedStart, $plannedEnd); - if ($today >= $endDate) { - $endDate = $today; - $bobotPlanning = (int) $activity->bobot_planning; - $rerataBobot = $duration > 0 ? $bobotPlanning / $duration : 0; - $bobotActual = (int) $activity->persentase_progress/100 * $bobotPlanning; - $sisaBobot = $bobotPlanning - $bobotActual; - $sisaHari = $rerataBobot > 0 ? $sisaBobot / $rerataBobot : 0; - $endDate->modify("+".ceil($sisaHari)." Days"); - $actualDuration = MasterFunctionsHelper::countDays($ganttId, $startDate, $endDate); - $activity->duration = $actualDuration; - $activity->end_date = $endDate; - $activity->save(); - } - } - } + if (isset($activity->planned_start) && isset($activity->planned_end) && $statusActivity != "done") { + // todo check report for no report / progress == 0 + $today = new DateTime(); + $endDate = new DateTime($activity->end_date); + $startDate = new DateTime($activity->start_date); + $plannedStart = new DateTime($activity->planned_start); + $plannedEnd = new DateTime($activity->planned_end); + $duration = MasterFunctionsHelper::countDays($ganttId, $plannedStart, $plannedEnd); + if ($today >= $endDate) { + $endDate = $today; + $bobotPlanning = (int) $activity->bobot_planning; + $rerataBobot = $duration > 0 ? $bobotPlanning / $duration : 0; + $bobotActual = (int) $activity->persentase_progress / 100 * $bobotPlanning; + $sisaBobot = $bobotPlanning - $bobotActual; + $sisaHari = $rerataBobot > 0 ? $sisaBobot / $rerataBobot : 0; + $endDate->modify("+" . ceil($sisaHari) . " Days"); + $actualDuration = MasterFunctionsHelper::countDays($ganttId, $startDate, $endDate); + $activity->duration = $actualDuration; + $activity->end_date = $endDate; + $activity->save(); + } + } + } return response()->json(['status' => 'success', 'message' => 'Activities Updated!', 'code' => 200], 200); - } + } public function batchUpdate(Request $request, $ganttId) { $entities = $request->all(); if (empty($ganttId) || !is_int((int) $ganttId)) return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); - $activity = Activity::where('version_gantt_id',$ganttId)->get(); + $activity = Activity::where('version_gantt_id', $ganttId)->get(); $link = Link::where('version_gantt_id', $ganttId)->get(); if (!$activity) return response()->json(['status' => 'failed', 'message' => 'Activity not found!', 'code' => 404], 404); @@ -604,7 +607,7 @@ class ActivityController extends Controller $activityToUpdate = $activity->firstWhere('id', $entity['data']['id']); $entity['data']['name'] = $entity['data']['text']; $entity['data']['persentase_progress'] = $entity['data']['progress'] * 100; - $entity['data']['type_activity'] = $entity['data']['type']; + $entity['data']['type_activity'] = $entity['data']['type'] ?? 'task'; if (isset($entity['data']['rencana_biaya'])) { $entity['data']['rencana_biaya'] = str_replace(",", ".", $entity['data']['rencana_biaya']); } @@ -627,25 +630,25 @@ class ActivityController extends Controller { if (!$data = Activity::find($id)) return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 404], 404); - $this->deleteRelative($id); + $this->deleteRelative($id); if (!$data->delete()) return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'data activity failed deleted!', 'code' => 500], 500); return response()->json(['status' => 'success', "action" => "deleted", 'message' => 'data activity successfully deleted!', 'code' => 200], 200); } - private function deleteRelative($activity_id) + private function deleteRelative($activity_id) { - UserToActivity::where('activity_id', $activity_id)->delete(); - AssignMaterial::where('activity_id', $activity_id)->delete(); - $dataAd = ActivityDokumen::where("activity_id", $activity_id)->get(); + UserToActivity::where('activity_id', $activity_id)->delete(); + AssignMaterial::where('activity_id', $activity_id)->delete(); + $dataAd = ActivityDokumen::where("activity_id", $activity_id)->get(); foreach ($dataAd as $ad) { - if(file_exists($this->pathActivityDocument.$ad->file)){ - unlink($this->pathActivityDocument.$ad->file); + if (file_exists($this->pathActivityDocument . $ad->file)) { + unlink($this->pathActivityDocument . $ad->file); } } - ActivityDokumen::where("activity_id", $activity_id)->delete(); - } + ActivityDokumen::where("activity_id", $activity_id)->delete(); + } public function getUpdate($id) { @@ -667,24 +670,24 @@ class ActivityController extends Controller return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } - public function searchAnalysisPrep(Request $request) + public function searchAnalysisPrep(Request $request) { $data = $request->all(); - $dataGet = DB::table('m_activity') - ->select('m_activity.name') - ->where('m_activity.proyek_id', $data['columns'][0]['value']) - ->where('m_activity.type_activity', 'task') - // ->where('m_activity.persentase_progress', '>', 0) - ->groupByRaw('m_activity.name') - ->get(); - return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet ], 200); + $dataGet = DB::table('m_activity') + ->select('m_activity.name') + ->where('m_activity.proyek_id', $data['columns'][0]['value']) + ->where('m_activity.type_activity', 'task') + // ->where('m_activity.persentase_progress', '>', 0) + ->groupByRaw('m_activity.name') + ->get(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet], 200); } - public function searchAnalysis(Request $request) + public function searchAnalysis(Request $request) { $dataBuilder = $this->setUpPayload($request->all(), 'm_activity'); $builder = $dataBuilder['builder']; - $dataGet = $builder->select( + $dataGet = $builder->select( 'selfTable.name', 'persentase_progress', 'selfTable.start_date', @@ -718,7 +721,7 @@ class ActivityController extends Controller ->groupBy('assign_material_to_activity.id') ->groupBy('user_names.user_name') ->get(); - return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet ], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet], 200); } // before upload file public function importOld(Request $request) @@ -777,8 +780,7 @@ class ActivityController extends Controller $data['activities'][$key]['weight'] = $parentWeight / $siblingsCount; } - } - ; + }; } $projectStart = Project::select('mulai_proyek')->where('id', $projectId)->first(); foreach ($data['activities'] as $i => $activity_row) { @@ -1137,7 +1139,6 @@ class ActivityController extends Controller 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); } From 14d75efdc52d7fc672c36715e1a0ba1ebbdd8bbb Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 27 Dec 2023 19:06:09 +0700 Subject: [PATCH 060/155] remove company_id ospro general --- app/Http/Controllers/CompanyController.php | 110 ---------- app/Http/Controllers/Controller.php | 1 - .../Controllers/MenuCompanyController.php | 195 ------------------ app/Models/Company.php | 37 ---- app/Models/HumanResource.php | 1 - app/Models/MenuCompany.php | 27 --- app/Models/ProjectRole.php | 2 +- app/Models/Role.php | 2 +- app/Models/RoleMenu.php | 2 +- app/Models/Satuan.php | 2 +- 10 files changed, 4 insertions(+), 375 deletions(-) delete mode 100644 app/Http/Controllers/CompanyController.php delete mode 100644 app/Http/Controllers/MenuCompanyController.php delete mode 100644 app/Models/Company.php delete mode 100644 app/Models/MenuCompany.php diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php deleted file mode 100644 index 7e8938d..0000000 --- a/app/Http/Controllers/CompanyController.php +++ /dev/null @@ -1,110 +0,0 @@ -validate($request, [ - 'name' => 'required', - 'description' => 'required' - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = Company::create($data); - - if ($result) { - return response()->json(['status' => 'success', 'message' => 'add Company successfully!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'add data Company 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 = Company::find($id); - - if ($result) { - return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'failed get data Company, 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 = Company::find($id); - - if ($data) { - $result = $data->update($request->all()); - } else { - return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); - die(); - } - - - if ($result) { - return response()->json(['status' => 'success', 'message' => 'data Company successfully updated!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'data Company failed updated!', 'code' => 400], 400); - } - } - - public function delete($id) - { - $data = Company::find($id); - - if ($data) { - $delete = $data->delete(); - } else { - return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); - die(); - } - - - if ($delete) { - return response()->json(['status' => 'success', 'message' => 'data Company successfully deleted!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'data Company failed deleted!', 'code' => 400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_company'); - $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 = Company::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 Company, please try again later!', 'code' => 400], 400); - } - } -} diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 50966ce..a084601 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -33,7 +33,6 @@ class Controller extends BaseController $this->currentDate = date("Y-m-d H:i:s"); $this->currentName = auth()->user() ? auth()->user()->name : "system"; $this->currentId = auth()->user() ? auth()->user()->id : 0; - $this->companyId = auth()->user() ? auth()->user()->company_id : 0; $this->pathImage = config('assets.image'); $this->pathDocument = config('assets.project'); $this->pathActivityDocument = config('assets.activity'); diff --git a/app/Http/Controllers/MenuCompanyController.php b/app/Http/Controllers/MenuCompanyController.php deleted file mode 100644 index 2b79748..0000000 --- a/app/Http/Controllers/MenuCompanyController.php +++ /dev/null @@ -1,195 +0,0 @@ -validate($request, [ - // 'icon' => 'required', - // 'name' => 'string|required', - // 'url' => 'required|unique:m_company_menu,url', - // 'sequence' => 'required|integer', - // ]); - - // $data = $request->all(); - - // $data['created_by'] = $this->currentName; - - // $result = MenuCompany::create($data); - - // if ($result) { - // return response()->json(['status' => 'success', 'message' => 'add data menu successfully!', 'code' => 200], 200); - // } else { - // return response()->json(['status' => 'failed', 'message' => 'add data menu failed!', 'code' => 400], 400); - // } - // } - - public function addMultiple(Request $request) - { - $menus = $request->all(); - - if (is_array($menus) && count($menus) > 0) { - $countRes = 0; - foreach ($menus as $menu) { - - $dataInsert = array( - "menu_id" => $menu['menu_id'], - "parent_menu_id" => $menu['parent_id'], - "company_id" => $menu['company_id'], - "icon" => $menu['icon'], - "alias_name" => $menu['alias_name'], - "url" => $menu['url'], - "sequence" => $menu['sequence'], - "created_by" => $this->currentName - ); - - $result = MenuCompany::create($dataInsert); - - if ($result) { - $countRes++; - } else { - $countRes--; - } - } - - if ($countRes > 0) { - return response()->json(['status' => 'success', 'message' => 'add data menu successfully!', 'code' => 200]); - } else { - return response()->json(['status' => 'failed', 'message' => 'add data menu failed created!', 'code' => 400]); - } - } else { - return response()->json(['status' => 'failed', 'message' => 'add data menu failed created!', 'code' => 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 = MenuCompany::find($id); - - if ($result) { - return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'failed get data menu, 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); - } - $this->validate($request, [ - 'icon' => 'required', - 'sequence' => 'required|integer', - ]); - $data = MenuCompany::find($id); - - - if ($data) { - $result = $data->update($request->all()); - } else { - return response()->json(['status' => 'failed', 'message' => 'data menu not found!', 'code' => 400], 400); - die(); - } - - - if ($result) { - return response()->json(['status' => 'success', 'message' => 'data menu successfully updated!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'data menu failed updated!', 'code' => 400], 400); - } - } - - public function delete($id) - { - $data = MenuCompany::find($id); - - if ($data) { - $delete = $data->delete(); - } else { - return response()->json(['status' => 'failed', 'message' => 'data menu not found!', 'code' => 400], 400); - die(); - } - - - if ($delete) { - return response()->json(['status' => 'success', 'message' => 'data menu successfully deleted!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'data menu failed deleted!', 'code' => 400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_company_menu'); - $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 listMenu($id) - { - $dataParent = RoleMenu::select("m_company_menu.*") - ->join('m_company_menu', 'm_company_menu.id', '=', 't_roles_menu.menu_id') - ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') - ->whereNull('m_company_menu.parent_id') - ->where('m_roles.id', $id) - ->orderBy('m_company_menu.sequence', 'ASC') - ->get(); - - $finalData = []; - foreach ($dataParent as $data) { - $data->children = $this->getChildrenMenu($data->id, $id); - $finalData[] = $data; - } - - return response()->json(['status' => 'success', 'code' => 200, 'data' => $finalData], 200); - } - - protected function getChildrenMenu($id, $role_id) - { - $dataChildren = RoleMenu::select("m_company_menu.*") - ->join('m_company_menu', 'm_company_menu.id', '=', 't_roles_menu.menu_id') - ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') - ->where('m_roles.id', $role_id) - ->where('m_company_menu.parent_id', $id) - ->orderBy('m_company_menu.sequence', 'ASC') - ->get(); - $children = []; - if ($dataChildren) { - foreach ($dataChildren as $data) { - $data->children = $this->getChildrenMenu($data->id, $role_id); - $children[] = $data; - } - } - return $children; - } - - public function list() - { - $data = MenuCompany::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 menu, please try again later!', 'code' => 400], 400); - } - } -} diff --git a/app/Models/Company.php b/app/Models/Company.php deleted file mode 100644 index db52f7d..0000000 --- a/app/Models/Company.php +++ /dev/null @@ -1,37 +0,0 @@ - Date: Wed, 27 Dec 2023 19:09:30 +0700 Subject: [PATCH 061/155] make new end point for project-cost --- app/Http/Controllers/ProjectController.php | 11 +++++++++++ routes/web.php | 1 + 2 files changed, 12 insertions(+) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 74dfd8d..a1feb5f 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -760,6 +760,17 @@ class ProjectController extends Controller return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } + public function getProjectCostIntegration($name) + { + $search = urlencode($name); + if (empty($search)) + return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); + $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); + + $response = MasterFunctionsHelper::curlReq($url); + return response()->json(['status' => 'success', 'data' => $response, 'code' => 200], 200); + } + private function httpReq($search) { $ch = curl_init(); diff --git a/routes/web.php b/routes/web.php index 7adfb7a..5b8aff6 100644 --- a/routes/web.php +++ b/routes/web.php @@ -74,6 +74,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/project/get-overdue-activities', 'ProjectController@getOverdueActivities'); $router->post('/project/get-integration-invoice', 'ProjectController@getInvoiceIntegration'); $router->post('/project/get-report-distribution', 'ProjectController@getReportDistribution'); + $router->get('/project/get-integration-project-cost={name}', 'ProjectController@getProjectCostIntegration'); /* $router->get('/project/get-expenditure/{id}/{date?}', 'ProjectController@getExpenditure'); */ From 3cdae71bd7dd9ebadc881e823d34555cf9b5fc86 Mon Sep 17 00:00:00 2001 From: wahyu Date: Thu, 28 Dec 2023 11:09:20 +0700 Subject: [PATCH 062/155] user to activity update filter --- app/Http/Controllers/UserToActivityController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index bbd1b40..bfe4f22 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -200,8 +200,8 @@ class UserToActivityController extends Controller ->join('m_version_gantt as mvg', 'mvg.id', '=', 'ma.version_gantt_id') ->join('m_proyek as mp', 'mp.id', '=', 'ma.proyek_id') ->where('ahta.user_id', $payload['user_id']) - ->where('ma.start_date', '<=', $payload['start_date']) - ->where('ma.end_date', '>=', $payload['end_date']) + ->where('ma.start_date', '<=', $payload['end_date']) + ->where('ma.end_date', '>=', $payload['start_date']) ->where('ma.proyek_id', $payload['proyek_id']) ->get(); From 6e66ad594ebd74974dc5397dcb133729aaeef3d2 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 11 Jan 2024 22:47:13 +0700 Subject: [PATCH 063/155] update filter project --- .../Controllers/DashboardBoDController.php | 82 +++++++++---------- 1 file changed, 40 insertions(+), 42 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index ab2a278..90a2375 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -122,9 +122,9 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerScheduleHealth($year = '%') + public function getTotalProjectPerScheduleHealth() { - $year = $this->interpolateYear($year); + // $year = $this->interpolateYear($year); $return = [ 'behind-schedule' => 0, @@ -132,7 +132,7 @@ class DashboardBoDController extends Controller 'on-schedule' => 0, ]; - $projects = Project::where('mulai_proyek', 'like', $year)->get(); + $projects = Project::get(); foreach ($projects as $index => $project) { $project->scurve = MasterFunctionsHelper::getSCurve($project->id); $selisihProgress = 0; @@ -165,9 +165,9 @@ class DashboardBoDController extends Controller return response()->json(['data' => $return, 'q' => $projects], 200); } - public function getTotalProjectScheduleHealthPerDivision($year = '%') + public function getTotalProjectScheduleHealthPerDivision() { - $year = $this->interpolateYear($year); + // $year = $this->interpolateYear($year); $divisions = Divisi::whereNull('parent')->get(); foreach ($divisions as $index => $division) { @@ -175,7 +175,7 @@ class DashboardBoDController extends Controller $scheduleData = new Collection(); $behindSchedule = $warning = $onSchedule = 0; - $projects = Project::where('mulai_proyek', 'like', $year)->where('divisi_id', $division->id)->get(); + $projects = Project::where('divisi_id', $division->id)->get(); foreach ($projects as $project) { $project->scurve = MasterFunctionsHelper::getSCurve($project->id); $selisihProgress = 0; @@ -210,31 +210,30 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerBudgetHealth($year = '%') + public function getTotalProjectPerBudgetHealth() { - $year = $this->interpolateYear($year); return response()->json([ 'data' => [ - 'overrun' => Project::where('mulai_proyek', 'like', $year)->where('budget_health', 'overrun')->count(), - 'warning' => Project::where('mulai_proyek', 'like', $year)->where('budget_health', 'warning')->count(), - 'on-budget' => Project::where('mulai_proyek', 'like', $year)->where('budget_health', 'on-budget')->count(), + 'overrun' => Project::where('budget_health', 'overrun')->count(), + 'warning' => Project::where('budget_health', 'warning')->count(), + 'on-budget' => Project::where('budget_health', 'on-budget')->count(), ] ], 200); } - private function countTotalProjectByBudgetHealthInDivision($divisi, $year, $health) + private function countTotalProjectByBudgetHealthInDivision($divisi, $health) { return Project::where('divisi_id', $divisi) - ->where('mulai_proyek', 'like', $year) + // ->where('mulai_proyek', 'like', $year) /* ->orWhere('akhir_proyek', 'like', $year) */ ->where('budget_health', $health) ->count(); } - public function getTotalProjectBudgetHealthPerDivision($year = '%') + public function getTotalProjectBudgetHealthPerDivision() { - $year = $this->interpolateYear($year); + // $year = $this->interpolateYear($year); $divisions = Divisi::select('id', 'name') ->with('children') ->whereNull('parent') @@ -242,13 +241,13 @@ class DashboardBoDController extends Controller // to do : count in more than 1 level child foreach ($divisions as $division) { $budgetData = new Collection(); - $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, $year, 'overrun'), 'overrun'); - $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, $year, 'warning'), 'warning'); - $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, $year, 'on-budget'), 'on-budget'); + $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, 'overrun'), 'overrun'); + $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, 'warning'), 'warning'); + $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, 'on-budget'), 'on-budget'); foreach ($division->children as $d) { - $budgetData['overrun'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, $year, 'overrun'); - $budgetData['warning'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, $year, 'warning'); - $budgetData['on-budget'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, $year, 'on-budget'); + $budgetData['overrun'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, 'overrun'); + $budgetData['warning'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, 'warning'); + $budgetData['on-budget'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, 'on-budget'); } unset($division->children); $division->budgetData = $budgetData; @@ -262,13 +261,13 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerPhase($year = '%') + public function getTotalProjectPerPhase() { - $year = $this->interpolateYear($year); + // $year = $this->interpolateYear($year); $projectPhases = ProjectPhase::orderBy('order')->get(); foreach ($projectPhases as $phase) { $phase->totalProject = Project::where('phase_id', $phase->id) - ->where('mulai_proyek', 'like', $year) + // ->where('mulai_proyek', 'like', $year) /* ->orWhere('akhir_proyek', 'like', $year) */ ->count(); } @@ -279,16 +278,16 @@ class DashboardBoDController extends Controller ], 200); } - private function countTotalProjectInDivision($id, $year) + private function countTotalProjectInDivision($id) { return Project::where('divisi_id', $id) - ->where('mulai_proyek', 'like', $year) + // ->where('mulai_proyek', 'like', $year) ->count(); } - public function getTotalProjectPerDivision($year = '%') + public function getTotalProjectPerDivision() { - $year = $this->interpolateYear($year); + // $year = $this->interpolateYear($year); $divisions = Divisi::select('id', 'name', 'parent', 'color') ->with('children') @@ -297,9 +296,9 @@ class DashboardBoDController extends Controller // to do : count in more than 1 level child foreach ($divisions as $v) { - $v->total = $this->countTotalProjectInDivision($v->id, $year); + $v->total = $this->countTotalProjectInDivision($v->id); foreach ($v->children as $d) { - $v->total += $this->countTotalProjectInDivision($d->id, $year); + $v->total += $this->countTotalProjectInDivision($d->id); } unset($v->children); } @@ -309,20 +308,18 @@ class DashboardBoDController extends Controller ], 200); } - private function countTotalProjectValueInDivision($id, $year) + private function countTotalProjectValueInDivision($id) { return Project::select(DB::raw("SUM(CAST(REPLACE(rencana_biaya, ',', '.') AS DOUBLE PRECISION))")) - ->where('mulai_proyek', 'like', $year) + // ->where('mulai_proyek', 'like', $year) /* ->orWhere('akhir_proyek', 'like', $year) */ ->where('divisi_id', $id) ->pluck('sum') ->first(); } - public function getTotalProjectValuePerDivision($year = '%') + public function getTotalProjectValuePerDivision() { - $year = $this->interpolateYear($year); - $divisions = Divisi::select('id', 'name', 'color') ->with('children') ->whereNull('parent') @@ -330,9 +327,9 @@ class DashboardBoDController extends Controller // to do : count in more than 1 level child foreach ($divisions as $v) { - $v->total = $this->countTotalProjectValueInDivision($v->id, $year); + $v->total = $this->countTotalProjectValueInDivision($v->id); foreach ($v->children as $d) { - $v->total += $this->countTotalProjectValueInDivision($d->id, $year); + $v->total += $this->countTotalProjectValueInDivision($d->id); } unset($v->children); } @@ -343,12 +340,13 @@ class DashboardBoDController extends Controller } - public function getDetailExpenditure($year = '%') + public function getDetailExpenditure() { - $year = $this->interpolateYear($year); - $projects = Project::select('m_proyek.*', 'md.name as divisi_name') - ->where('mulai_proyek', 'like', $year) - ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') + // $year = $this->interpolateYear($year); + $projects = Project::select('m_proyek.*', 'md.name as divisi_name', 'tpy.name as project_type_name') + // ->where('mulai_proyek', 'like', $year) + ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') + ->join('m_type_proyek as tpy', 'tpy.id', '=', 'm_proyek.type_proyek_id') ->orderBy('id', 'desc') ->get(); foreach ($projects as $project) { From 215142ec386b95376fe34b88c37a3f6fb415a105 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 11 Jan 2024 22:47:20 +0700 Subject: [PATCH 064/155] add childern --- app/Http/Controllers/DivisiController.php | 92 +++++++++++++---------- 1 file changed, 54 insertions(+), 38 deletions(-) diff --git a/app/Http/Controllers/DivisiController.php b/app/Http/Controllers/DivisiController.php index 2d056aa..2212549 100644 --- a/app/Http/Controllers/DivisiController.php +++ b/app/Http/Controllers/DivisiController.php @@ -8,21 +8,23 @@ use App\Models\Divisi; class DivisiController extends Controller { - private function getAllChildren($divisi, $depth = 0, $array = []) { + private function getAllChildren($divisi, $depth = 0, $array = []) + { $divisi->depth = $depth; array_push($array, $divisi); - foreach($divisi->children as $child){ + foreach ($divisi->children as $child) { $array = $this->getAllChildren($child, $depth + 1, $array); } return $array; } - public function add(Request $request){ + public function add(Request $request) + { $this->validate($request, [ 'name' => 'string|required|unique:m_divisi,name', 'description' => 'nullable|string', 'parent' => 'nullable|integer', - 'color'=>'nullable|string|max:10' + 'color' => 'nullable|string|max:10' ]); $data = $request->all(); @@ -30,15 +32,16 @@ class DivisiController extends Controller $result = Divisi::create($data); - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add data','code'=> 500]); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Failed to add data', 'code' => 500]); - return response()->json(['status'=>'success','message'=>'Data created!','code'=>200]); + 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); + 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); $this->validate($request, [ 'name' => 'string|required', @@ -47,46 +50,59 @@ class DivisiController extends Controller ]); $data = Divisi::find($id); - $request->name !== $data['name'] ? $this->validate($request,['name'=>'unique:m_divisi,name']) : ''; + $request->name !== $data['name'] ? $this->validate($request, ['name' => 'unique:m_divisi,name']) : ''; - if(!$data) - return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + 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); + if (!$result) + return response()->json(['status' => 'failed', 'message' => 'Update failed!', 'code' => 500], 500); - return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); + 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); + 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); + 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); + if (!$delete) + return response()->json(['status' => 'failed', 'message' => 'Delete failed!', 'code' => 500], 500); - return response()->json(['status'=>'success','message'=> 'Data deleted!','code'=> 200], 200); + 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); + { + $parentDivisi = Divisi::whereNull('parent')->with('children')->get(); + $divisions = []; + foreach ($parentDivisi as $objRow) { + $objRow->children = $this->getAllChildren($objRow); + // $objRow->key = rand(1, 1000); + $divisions[] = $objRow; + } + $countData = count($divisions); + if ($countData == 0) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + + return response()->json(['status' => 'success', 'code' => 200, 'data' => $divisions, 'totalRecord' => $countData], 200); + + // $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); //return $this->list(); // cant use builder for this case } @@ -95,20 +111,20 @@ class DivisiController extends Controller { $parentMenus = Divisi::whereNull('parent')->with('children')->get(); $divisions = []; - foreach($parentMenus as $menu){ + foreach ($parentMenus as $menu) { $childs = $this->getAllChildren($menu); - foreach($childs as $d){ + foreach ($childs as $d) { $d->displayName = ' ' . $d->name; - for($i=0; $i < $d->depth; $i++){ - $d->displayName = '--' . $d->displayName ; + for ($i = 0; $i < $d->depth; $i++) { + $d->displayName = '--' . $d->displayName; } array_push($divisions, $d); } } $countData = count($divisions); - if($countData == 0) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + if ($countData == 0) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - return response()->json(['status'=>'success','code'=>200,'data'=> $divisions, 'totalRecord'=> $countData], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $divisions, 'totalRecord' => $countData], 200); } } From caac6506f89eb6207d4f78d40d37f05ede646b00 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 11 Jan 2024 22:47:30 +0700 Subject: [PATCH 065/155] add sponsor --- app/Http/Controllers/ProjectController.php | 20 +++++++++++--------- app/Models/Project.php | 3 ++- routes/web.php | 20 ++++++++++---------- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 719908c..7d89879 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -123,7 +123,8 @@ class ProjectController extends Controller 'phase_id', 'calculation_status', 'md.name as divisi_name', - 'nickname' + 'nickname', + 'sponsor' ) ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') ->where('m_proyek.id', $id) @@ -322,7 +323,8 @@ class ProjectController extends Controller 'created_at', 'created_by', 'updated_at', - 'updated_by' + 'updated_by', + 'sponsor' )->orderBy('id', 'desc') // ->where("created_by",$this->currentName) ->get(); @@ -620,19 +622,19 @@ class ProjectController extends Controller // } - $plannedStart = Activity::where('version_gantt_id', $ganttId) - ->orderBy('planned_start') - ->value('planned_start'); - $plannedEnd = Activity::where('version_gantt_id', $ganttId) - ->orderByDesc('planned_end') - ->value('planned_end'); + $plannedStart = Activity::where('version_gantt_id', $ganttId) + ->orderBy('planned_start') + ->value('planned_start'); + $plannedEnd = Activity::where('version_gantt_id', $ganttId) + ->orderByDesc('planned_end') + ->value('planned_end'); if (isset($result->header)) { $result->header->start_date = $startDate; $result->header->end_date = $maxEndDate->end_date; $result->header->planned_start = $plannedStart; $result->header->planned_end = $plannedEnd; } - return response()->json(['status'=>'success','code'=> 200,'data'=>$result, 'gantt'=>$ganttId], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result, 'gantt' => $ganttId], 200); } public function getOverdueActivities(Request $request) diff --git a/app/Models/Project.php b/app/Models/Project.php index 2ac0fd5..55e5f55 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -51,6 +51,7 @@ class Project extends Model 'created_by', 'updated_at', 'updated_by', - 'created_by_id' + 'created_by_id', + 'sponsor' ]; } diff --git a/routes/web.php b/routes/web.php index 5b8aff6..cb953bd 100644 --- a/routes/web.php +++ b/routes/web.php @@ -23,16 +23,16 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->group(['middleware' => ['auth', 'cors']], function () use ($router) { - $router->get('/dashboard/get-company-cashflow[/{year}]', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure - $router->get('/dashboard/get-invoice-outstanding[/{year}]', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in - $router->get('/dashboard/get-total-project-per-schedule-health[/{year}]', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); - $router->get('/dashboard/get-total-project-per-budget-health[/{year}]', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); - $router->get('/dashboard/get-total-project-schedule-health-per-division[/{year}]', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); - $router->get('/dashboard/get-total-project-budget-health-per-division[/{year}]', 'DashboardBoDController@getTotalProjectBudgetHealthPerDivision'); - $router->get('/dashboard/get-total-project-per-phase[/{year}]', 'DashboardBoDController@getTotalProjectPerPhase'); - $router->get('/dashboard/get-total-project-per-division[/{year}]', 'DashboardBoDController@getTotalProjectPerDivision'); - $router->get('/dashboard/get-total-project-value-per-division[/{year}]', 'DashboardBoDController@getTotalProjectValuePerDivision'); - $router->get('/dashboard/get-detail-expenditure[/{year}]', 'DashboardBoDController@getDetailExpenditure'); + $router->get('/dashboard/get-company-cashflow', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure + $router->get('/dashboard/get-invoice-outstanding', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in + $router->get('/dashboard/get-total-project-per-schedule-health', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); + $router->get('/dashboard/get-total-project-per-budget-health', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); + $router->get('/dashboard/get-total-project-schedule-health-per-division', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); + $router->get('/dashboard/get-total-project-budget-health-per-division', 'DashboardBoDController@getTotalProjectBudgetHealthPerDivision'); + $router->get('/dashboard/get-total-project-per-phase', 'DashboardBoDController@getTotalProjectPerPhase'); + $router->get('/dashboard/get-total-project-per-division', 'DashboardBoDController@getTotalProjectPerDivision'); + $router->get('/dashboard/get-total-project-value-per-division', 'DashboardBoDController@getTotalProjectValuePerDivision'); + $router->get('/dashboard/get-detail-expenditure', 'DashboardBoDController@getDetailExpenditure'); $router->post('/role/search', 'RoleController@search'); $router->post('/role/add', 'RoleController@add'); From e2e06760928519e0018b4c96f5902495034e7e04 Mon Sep 17 00:00:00 2001 From: farhantock Date: Fri, 19 Jan 2024 11:19:23 +0700 Subject: [PATCH 066/155] add new response appConfig --- app/Http/Controllers/AuthController.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 37ae48f..7ef300e 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Hash; use App\Models\User; use App\Models\Role; +use App\Models\Company; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Password; use Illuminate\Validation\ValidationException; @@ -58,6 +59,10 @@ class AuthController extends Controller $dataRole = Role::find($user->role_id); $dataHierarchy = $this->getDataHierarchy($user->divisi_id, $user->id); + $configApp = Company::where('id', $user->company_id)->first(); + + if ($configApp) + $user->configApp = $configApp; if ($dataRole) $user->role = $dataRole; From 136fb42da4e0276c4ae3547d15bd76c351107014 Mon Sep 17 00:00:00 2001 From: farhantock Date: Fri, 19 Jan 2024 11:19:34 +0700 Subject: [PATCH 067/155] add field company_id in models --- app/Models/Absent.php | 2 +- app/Models/Broadcast.php | 2 +- app/Models/Company.php | 3 ++- app/Models/PanicButton.php | 4 ++-- app/Models/Presence.php | 6 +++--- app/Models/ReportK3.php | 11 ++++++----- 6 files changed, 15 insertions(+), 13 deletions(-) diff --git a/app/Models/Absent.php b/app/Models/Absent.php index c8af929..89aa095 100644 --- a/app/Models/Absent.php +++ b/app/Models/Absent.php @@ -12,6 +12,6 @@ class Absent extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'user_id', 'description', 'created_at', 'created_by', 'updated_at', 'updated_by' + 'user_id', 'description', 'created_at', 'created_by', 'updated_at', 'updated_by', 'company_id' ]; } diff --git a/app/Models/Broadcast.php b/app/Models/Broadcast.php index bacbdcd..d1c7ed0 100644 --- a/app/Models/Broadcast.php +++ b/app/Models/Broadcast.php @@ -12,6 +12,6 @@ class Broadcast extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'title_notif', 'message_notif', 'description', 'send_to_type', 'send_to_id', 'status_send', 'created_at', 'created_by', 'updated_at', 'updated_by' + 'title_notif', 'message_notif', 'description', 'send_to_type', 'send_to_id', 'status_send', 'created_at', 'created_by', 'updated_at', 'updated_by', 'company_id' ]; } diff --git a/app/Models/Company.php b/app/Models/Company.php index 2dc38e5..7593aed 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -31,6 +31,7 @@ class Company extends Model 'created_at', 'created_by', 'updated_at', - 'updated_by' + 'updated_by', + 'date_register' ]; } diff --git a/app/Models/PanicButton.php b/app/Models/PanicButton.php index 361bf79..51e1e2a 100644 --- a/app/Models/PanicButton.php +++ b/app/Models/PanicButton.php @@ -12,6 +12,6 @@ class PanicButton extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'user_id', 'lat', 'lon', 'status_response', 'description', 'created_at', 'created_by', 'updated_at', 'updated_by' - ]; + 'user_id', 'lat', 'lon', 'status_response', 'description', 'created_at', 'created_by', 'updated_at', 'updated_by', 'company_id' + ]; } diff --git a/app/Models/Presence.php b/app/Models/Presence.php index 620a91e..e3fa1cd 100644 --- a/app/Models/Presence.php +++ b/app/Models/Presence.php @@ -13,9 +13,9 @@ class Presence extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'user_id', 'clock_in', 'clock_out', 'date_presence', + 'user_id', 'clock_in', 'clock_out', 'date_presence', 'clock_in_lat', 'clock_in_lng', 'clock_out_lat', 'clock_out_lng', - 'clock_in_loc', 'clock_out_loc','clock_in_boundary', 'clock_out_boundary', - 'created_at', 'created_by', 'updated_at', 'updated_by' + 'clock_in_loc', 'clock_out_loc', 'clock_in_boundary', 'clock_out_boundary', + 'created_at', 'created_by', 'updated_at', 'updated_by', 'company_id' ]; } diff --git a/app/Models/ReportK3.php b/app/Models/ReportK3.php index a2cc852..abf36e3 100644 --- a/app/Models/ReportK3.php +++ b/app/Models/ReportK3.php @@ -12,14 +12,15 @@ class ReportK3 extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'user_id', + 'user_id', 'description', 'proyek_id', 'report_date', 'description', - 'created_at', - 'created_by', - 'updated_at', - 'updated_by' + 'created_at', + 'created_by', + 'updated_at', + 'updated_by', + 'company_id' ]; } From 3cac7e236339bb7c76705e72e618942367952201 Mon Sep 17 00:00:00 2001 From: wahyun Date: Fri, 19 Jan 2024 11:43:51 +0700 Subject: [PATCH 068/155] adding company_id --- .../Controllers/HumanResourceController.php | 5 +- app/Http/Controllers/ProjectController.php | 5 +- .../Controllers/ProjectRoleController.php | 241 +++++++++--------- app/Http/Controllers/RoleController.php | 3 +- 4 files changed, 129 insertions(+), 125 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index be26a1c..6c78f6c 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -16,7 +16,8 @@ class HumanResourceController extends Controller 'role_id' => 'required', 'name' => 'required', 'ktp_number' => 'required|numeric|unique:m_users,ktp_number', - 'employee_type' => 'required' + 'employee_type' => 'required', + 'company_id' => 'required' ]); $data = $request->all(); @@ -118,7 +119,7 @@ class HumanResourceController extends Controller public function list() { - $data = HumanResource::select('id', 'name', 'role_id')->get(); + $data = HumanResource::select('id', 'name', 'role_id','company_id')->get(); $countData = $data->count(); if ($data) { diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index f4af843..c69e57d 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -53,7 +53,8 @@ class ProjectController extends Controller 'mulai_proyek' => 'required', 'akhir_proyek' => 'required', 'rencana_biaya' => 'required', - 'type_proyek_id' => 'required' + 'type_proyek_id' => 'required', + 'company_id' => 'required' ]); $data = $request->all(); @@ -83,7 +84,7 @@ class ProjectController extends Controller $result = Project::query() ->from('m_proyek AS mp') ->where('mp.id', $id) - ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); + ->selectRaw('value_proyek,mp.company_id,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); if (!is_null($result->first()['divisi_id'])) { $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') diff --git a/app/Http/Controllers/ProjectRoleController.php b/app/Http/Controllers/ProjectRoleController.php index e12586b..19be106 100644 --- a/app/Http/Controllers/ProjectRoleController.php +++ b/app/Http/Controllers/ProjectRoleController.php @@ -1,120 +1,121 @@ -validate($request, [ - 'name' => 'required', - 'description' => 'required' - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = ProjectRole::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'add data project role successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data project 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 = ProjectRole::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 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 = ProjectRole::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data project role not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data project role successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data project role failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = ProjectRole::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data project role not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data project role successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data project role failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_role_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 = ProjectRole::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 role, please try again later!','code'=>400], 400); - } - } - - public function select(Request $request){ - $search = $request->query('search'); - if($search && !empty($search)){ - $data = ProjectRole::where("name", 'like', '%'.$search.'%')->get(); - }else{ - $data = ProjectRole::all(); - } - - return response()->json($data); - } -} +validate($request, [ + 'name' => 'required', + 'description' => 'required', + 'company_id' => 'required' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = ProjectRole::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'add data project role successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add data project 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 = ProjectRole::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 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 = ProjectRole::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data project role not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data project role successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project role failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = ProjectRole::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data project role not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data project role successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project role failed deleted!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_role_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 = ProjectRole::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 role, please try again later!','code'=>400], 400); + } + } + + public function select(Request $request){ + $search = $request->query('search'); + if($search && !empty($search)){ + $data = ProjectRole::where("name", 'like', '%'.$search.'%')->get(); + }else{ + $data = ProjectRole::all(); + } + + return response()->json($data); + } +} diff --git a/app/Http/Controllers/RoleController.php b/app/Http/Controllers/RoleController.php index 7e6dbde..9b1c8b5 100644 --- a/app/Http/Controllers/RoleController.php +++ b/app/Http/Controllers/RoleController.php @@ -12,7 +12,8 @@ class RoleController extends Controller { $this->validate($request, [ 'name' => 'string|required|unique:m_roles,name,NULL,id,company_id,' . $request->input('company_id'), - 'description' => 'required' + 'description' => 'required', + 'company_id' => 'required' ]); $data = $request->all(); From 588305ebafdf0d4305d24152d84d9f5095228b0b Mon Sep 17 00:00:00 2001 From: wahyu Date: Fri, 19 Jan 2024 13:50:46 +0700 Subject: [PATCH 069/155] update report datatable --- app/Http/Controllers/ActivityController.php | 1 + .../Controllers/AssignMaterialController.php | 34 +++++++++++-------- .../ReportActivityMaterialController.php | 4 ++- 3 files changed, 23 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index e08ff7b..7b44585 100755 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -688,6 +688,7 @@ class ActivityController extends Controller 'selfTable.name', 'persentase_progress', 'selfTable.start_date', + 'selfTable.id', 'selfTable.end_date', 'selfTable.planned_start', 'selfTable.planned_end', diff --git a/app/Http/Controllers/AssignMaterialController.php b/app/Http/Controllers/AssignMaterialController.php index 3d78384..8916063 100644 --- a/app/Http/Controllers/AssignMaterialController.php +++ b/app/Http/Controllers/AssignMaterialController.php @@ -7,6 +7,7 @@ use App\Models\AssignMaterial; use App\Models\RequestMaterial; use App\Models\Activity; use App\Models\ReportActivityMaterial; +use Illuminate\Support\Facades\DB; use Datatables; class AssignMaterialController extends Controller @@ -140,28 +141,31 @@ class AssignMaterialController extends Controller $id_activity = $request->query('idact'); $data = AssignMaterial::select( - AssignMaterial::raw('SUM(qty_planning) as qty_planning'), + DB::raw('(SELECT SUM(assign_material_to_activity.qty_planning) FROM assign_material_to_activity WHERE assign_material_to_activity.activity_id = ram.activity_id) as qty_planning'), + DB::raw('SUM(ram.qty) as qty_sum'), "m.description as material_name", "assign_material_to_activity.activity_id", - "assign_material_to_activity.type" - // "assign_material_to_activity.material_id", + "assign_material_to_activity.material_id", ) ->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") + ->groupBy("ram.activity_id") ->groupBy("assign_material_to_activity.activity_id") - ->groupBy("assign_material_to_activity.type") + ->groupBy("assign_material_to_activity.material_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('qty_planning', function($row){ + // $val_qty_act = AssignMaterial::select(ReportActivityMaterial::raw('SUM(ram.qty) as qty_sum'),"m.description as material_name1","m.id") + // ->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") + // ->groupBy("m.id") + // ->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') @@ -196,8 +200,8 @@ class AssignMaterialController extends Controller ->addColumn('action', function($row){ $dataPlan = AssignMaterial::select('assign_material_to_activity.id')->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") ->where('activity_id', $row->activity_id)->where('m.description', $row->material_name)->first(); - $actionBtn = ''; - $actionBtn .= ''; + $actionBtn = ''; + $actionBtn .= ''; return $actionBtn; }) ->rawColumns(['action'])->make(true); diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index 44b228b..b10cba7 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -136,6 +136,7 @@ class ReportActivityMaterialController extends Controller $id_am = $request->query('idAmi'); $type = $request->query('type'); $materialName = $request->query('materialName'); + $materialId = $request->query('materialId'); if($type == 'plan'){ $activity = Activity::findOrFail($id_activity); $baselineDuration = 0; @@ -146,6 +147,7 @@ class ReportActivityMaterialController extends Controller ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") ->where('assign_material_to_activity.activity_id', $id_activity) ->where('assign_material_to_activity.id', $id_am) + ->where('m.id', $materialId) ->orderBy('assign_material_to_activity.id', 'asc') ->get(); if ($baselineDuration > 0) { @@ -174,7 +176,7 @@ class ReportActivityMaterialController extends Controller ->join("m_req_material as m", "m.id", "=", "amta.material_id") ->join("m_users as u", "u.id", "=", "report_activity_material.user_id") ->where('report_activity_material.activity_id', $id_activity) - ->where('report_activity_material.assign_material_id', $id_am) + ->where('m.id', $materialId) ->orderBy('report_activity_material.report_date', 'asc') ->get(); if ($baselineDuration > 0) { From 537c532b77f9b16dd998a0473cf241577d47dad6 Mon Sep 17 00:00:00 2001 From: wahyu Date: Fri, 19 Jan 2024 16:27:56 +0700 Subject: [PATCH 070/155] update report datatable --- app/Http/Controllers/AssignMaterialController.php | 2 -- app/Http/Controllers/ReportActivityMaterialController.php | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/AssignMaterialController.php b/app/Http/Controllers/AssignMaterialController.php index 8916063..0d7b303 100644 --- a/app/Http/Controllers/AssignMaterialController.php +++ b/app/Http/Controllers/AssignMaterialController.php @@ -145,14 +145,12 @@ class AssignMaterialController extends Controller DB::raw('SUM(ram.qty) as qty_sum'), "m.description as material_name", "assign_material_to_activity.activity_id", - "assign_material_to_activity.material_id", ) ->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") ->groupBy("ram.activity_id") ->groupBy("assign_material_to_activity.activity_id") - ->groupBy("assign_material_to_activity.material_id") ->where("assign_material_to_activity.activity_id", $id_activity)->get(); return Datatables::of($data) ->addIndexColumn() diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index b10cba7..a55e15f 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -147,7 +147,7 @@ class ReportActivityMaterialController extends Controller ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") ->where('assign_material_to_activity.activity_id', $id_activity) ->where('assign_material_to_activity.id', $id_am) - ->where('m.id', $materialId) + ->where('m.description', $materialName) ->orderBy('assign_material_to_activity.id', 'asc') ->get(); if ($baselineDuration > 0) { @@ -176,7 +176,7 @@ class ReportActivityMaterialController extends Controller ->join("m_req_material as m", "m.id", "=", "amta.material_id") ->join("m_users as u", "u.id", "=", "report_activity_material.user_id") ->where('report_activity_material.activity_id', $id_activity) - ->where('m.id', $materialId) + ->where('m.description', $materialName) ->orderBy('report_activity_material.report_date', 'asc') ->get(); if ($baselineDuration > 0) { From 4cc57c18ec8acd2ccca7deb3805b3f05149f8202 Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 23 Jan 2024 11:59:02 +0700 Subject: [PATCH 071/155] update filter dashboard --- .../Controllers/DashboardBoDController.php | 405 ++++++++++-------- routes/web.php | 28 +- 2 files changed, 247 insertions(+), 186 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index d82a3e9..8e4c50a 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -58,30 +58,31 @@ class DashboardBoDController extends Controller return $response; } - public function getCompanyCashFlow($year = '%', $company_id, $all_project, $hierarchy) + public function getCompanyCashFlow($company_id, $all_project, $hierarchy, $role_name) { - $year = $this->interpolateYear($year); $totalExpenditure = $totalInvoice = $totalPaidInvoice = 0; $totalBudgets = null; - if ($all_project) { - $totalBudgets = Project::where('mulai_proyek', 'like', $year) - ->where('company_id', $company_id) + $role = urldecode($role_name); + if ($role === "Super Admin") { + $totalBudgets = Project::sum(DB::raw('CAST("rencana_biaya" AS DOUBLE PRECISION)')); + } elseif (!empty($all_project)) { + $totalBudgets = Project::where('company_id', $company_id) ->sum(DB::raw('CAST("rencana_biaya" AS DOUBLE PRECISION)')); } else { - $totalBudgets = Project::where('mulai_proyek', 'like', $year) - ->where('created_by_id', $hierarchy) + $totalBudgets = Project::where('created_by_id', $hierarchy) ->sum(DB::raw('CAST("rencana_biaya" AS DOUBLE PRECISION)')); } $projects = null; - if ($all_project) { - $projects = Project::where('mulai_proyek', 'like', $year) - ->where('company_id', $company_id) + + if ($role === "Super Admin") { + $projects = Project::get(); + } elseif (!empty($all_project)) { + $projects = Project::where('company_id', $company_id) ->get(); } else { - $projects = Project::where('mulai_proyek', 'like', $year) - ->where('created_by_id', $hierarchy) + $projects = Project::where('created_by_id', $hierarchy) ->get(); } @@ -114,24 +115,32 @@ class DashboardBoDController extends Controller ], 200); } - public function getDetailExpenditureColor($company_id) { - $query = ProjectExpenditure::where('company_id',$company_id)->get(); - $data = []; - foreach($query as $value) { - if($value['name'] === 'Total Budget') { - $data['total_budget'] = $value['color']; - } - if($value['name'] === 'Expenditure') { - $data['total_expenditure'] = $value['color']; - } - if($value['name'] === 'Invoice') { - $data['total_invoice'] = $value['color']; - } - if($value['name'] === 'Cash In') { - $data['total_paid_invoice'] = $value['color']; - } - } - return response()->json([ + public function getDetailExpenditureColor($role_name, $company_id) + { + $role = urldecode($role_name); + $query = null; + if ($role === 'Super Admin') { + $query = ProjectExpenditure::get(); + } else { + $query = ProjectExpenditure::where('company_id', $company_id)->get(); + } + + $data = []; + foreach ($query as $value) { + if ($value['name'] === 'Total Budget') { + $data['total_budget'] = $value['color']; + } + if ($value['name'] === 'Expenditure') { + $data['total_expenditure'] = $value['color']; + } + if ($value['name'] === 'Invoice') { + $data['total_invoice'] = $value['color']; + } + if ($value['name'] === 'Cash In') { + $data['total_paid_invoice'] = $value['color']; + } + } + return response()->json([ 'data' => [ 'total_budget' => $data['total_budget'] ?? '', 'total_expenditure' => $data['total_expenditure'] ?? '', @@ -139,85 +148,109 @@ class DashboardBoDController extends Controller 'total_paid_invoice' => $data['total_paid_invoice'] ?? '', ] ], 200); - } - - public function getDetailFinancialHealthColor($company_id) { - $query = ProjectFinancialHealth::where('company_id',$company_id)->get(); - $data = []; - foreach($query as $value) { - if($value['name'] === 'Cost Overrun') { - $data['overrun'] = $value['color']; - } - if($value['name'] === 'Early Warning') { - $data['warning'] = $value['color']; - } - if($value['name'] === 'On Budget') { - $data['on-budget'] = $value['color']; - } - } - return response()->json([ + } + + public function getDetailFinancialHealthColor($role_name, $company_id) + { + $role = urldecode($role_name); + $query = null; + if ($role === 'Super Admin') { + $query = ProjectFinancialHealth::get(); + } else { + $query = ProjectFinancialHealth::where('company_id', $company_id)->get(); + } + + + $data = []; + foreach ($query as $value) { + if ($value['name'] === 'Cost Overrun') { + $data['overrun'] = $value['color']; + } + if ($value['name'] === 'Early Warning') { + $data['warning'] = $value['color']; + } + if ($value['name'] === 'On Budget') { + $data['on-budget'] = $value['color']; + } + } + return response()->json([ 'data' => [ 'overrun' => $data['overrun'] ?? '', 'warning' => $data['warning'] ?? '', 'on-budget' => $data['on-budget'] ?? '', ] ], 200); - } - - public function getDetailScheduleHealthColor($company_id) { - $query = ProjectScheduleHealth::where('company_id',$company_id)->get(); - $data = []; - foreach($query as $value) { - if($value['name'] === 'Behind Schedule') { - $data['behind-schedule'] = $value['color']; - } - if($value['name'] === 'Early Warning') { - $data['warning'] = $value['color']; - } - if($value['name'] === 'On Schedule') { - $data['on-schedule'] = $value['color']; - } - } - return response()->json([ + } + + public function getDetailScheduleHealthColor($role_name, $company_id) + { + $role = urldecode($role_name); + $query = null; + if ($role === 'Super Admin') { + $query = ProjectScheduleHealth::get(); + } else { + $query = ProjectScheduleHealth::where('company_id', $company_id)->get(); + } + + $data = []; + foreach ($query as $value) { + if ($value['name'] === 'Behind Schedule') { + $data['behind-schedule'] = $value['color']; + } + if ($value['name'] === 'Early Warning') { + $data['warning'] = $value['color']; + } + if ($value['name'] === 'On Schedule') { + $data['on-schedule'] = $value['color']; + } + } + return response()->json([ 'data' => [ 'behind-schedule' => $data['behind-schedule'] ?? '', 'warning' => $data['warning'] ?? '', 'on-schedule' => $data['on-schedule'] ?? '', ] ], 200); - } - - public function getDetailInvoiceColor($company_id) { - $query = ProjectInvoice::where('company_id',$company_id)->get(); - $data = []; - foreach($query as $value) { - if($value['name'] === 'Invoiced') { - $data['invoiced'] = $value['color']; - } - if($value['name'] === 'Cash In') { - $data['paid'] = $value['color']; - } - } - return response()->json([ + } + + public function getDetailInvoiceColor($role_name, $company_id) + { + $role = urldecode($role_name); + $query = null; + if ($role === 'Super Admin') { + $query = ProjectInvoice::get(); + } else { + $query = ProjectInvoice::where('company_id', $company_id)->get(); + } + $data = []; + foreach ($query as $value) { + if ($value['name'] === 'Invoiced') { + $data['invoiced'] = $value['color']; + } + if ($value['name'] === 'Cash In') { + $data['paid'] = $value['color']; + } + } + return response()->json([ 'data' => [ 'invoiced' => $data['invoiced'] ?? '', 'paid' => $data['paid'] ?? '' ] ], 200); - } + } // integrasi - public function getInvoiceOutstanding($year = '%', $company_id, $all_project, $hierarchy) + public function getInvoiceOutstanding($role_name, $company_id, $all_project, $hierarchy) { - $year = $this->interpolateYear($year); + $role = urldecode($role_name); $projects = null; - if ($all_project) { - $projects = Project::where('mulai_proyek', 'like', $year) - ->where('company_id', $company_id) + if ($role === 'Super Admin') { + $projects = Project::get(); + } elseif (!empty($all_project)) { + $projects = Project::where('company_id', $company_id) ->get(); } else { - $projects = Project::where('mulai_proyek', 'like', $year) - ->where('created_by_id', $hierarchy) + $projects = Project::where('created_by_id', $hierarchy) ->get(); } @@ -241,9 +274,9 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerScheduleHealth($year = '%', $company_id, $all_project, $hierarchy) + public function getTotalProjectPerScheduleHealth($role_name, $company_id, $all_project, $hierarchy) { - $year = $this->interpolateYear($year); + $role = urldecode($role_name); $return = [ 'behind-schedule' => 0, @@ -252,13 +285,13 @@ class DashboardBoDController extends Controller ]; $projects = null; - if ($all_project) { - $projects = Project::where('mulai_proyek', 'like', $year) - ->where('company_id', $company_id) + if ($role === 'Super Admin') { + $projects = Project::get(); + } elseif ($all_project) { + $projects = Project::where('company_id', $company_id) ->get(); } else { - $projects = Project::where('mulai_proyek', 'like', $year) - ->where('created_by_id', $hierarchy) + $projects = Project::where('created_by_id', $hierarchy) ->get(); } @@ -294,20 +327,24 @@ class DashboardBoDController extends Controller return response()->json(['data' => $return, 'q' => $projects], 200); } - public function getTotalProjectScheduleHealthPerDivision($year = '%', $company_id) + public function getTotalProjectScheduleHealthPerDivision($role_name, $company_id) { - $year = $this->interpolateYear($year); - $divisions = Divisi::whereNull('parent') - ->where('company_id', $company_id) - ->whereNull('parent') - ->get(); - + $role = urldecode($role_name); + $divisions = null; + if ($role === 'Super Admin') { + $divisions = Divisi::whereNull('parent') + ->get(); + } else { + $divisions = Divisi::whereNull('parent') + ->where('company_id', $company_id) + ->get(); + } foreach ($divisions as $index => $division) { $scheduleData = new Collection(); $behindSchedule = $warning = $onSchedule = 0; - $projects = Project::where('mulai_proyek', 'like', $year)->where('divisi_id', $division->id)->get(); + $projects = Project::where('divisi_id', $division->id)->get(); foreach ($projects as $project) { $project->scurve = MasterFunctionsHelper::getSCurve($project->id); $selisihProgress = 0; @@ -342,9 +379,9 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerBudgetHealth($year = '%', $company_id, $all_project, $hierarchy) + public function getTotalProjectPerBudgetHealth($role_name, $company_id, $all_project, $hierarchy) { - $year = $this->interpolateYear($year); + $role = urldecode($role_name); $response = [ 'data' => [ 'overrun' => 0, @@ -353,81 +390,84 @@ class DashboardBoDController extends Controller ] ]; - if ($all_project) { - $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'overrun') - ->where('company_id', $company_id) + if ($role === 'Super Admin') { + $response['data']['overrun'] = Project::where('budget_health', 'overrun') ->count(); - } else { - $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'overrun') - ->where('created_by_id', $hierarchy) - ->count(); - } - if ($all_project) { - $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'overrun') + } elseif ($all_project) { + $response['data']['overrun'] = Project::where('budget_health', 'overrun') ->where('company_id', $company_id) ->count(); } else { - $response['data']['overrun'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'overrun') + $response['data']['overrun'] = Project::where('budget_health', 'overrun') ->where('created_by_id', $hierarchy) ->count(); } - if ($all_project) { - $response['data']['warning'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'warning') + + if ($role === 'Super Admin') { + $response['data']['overrun'] = Project::where('budget_health', 'warning') + ->count(); + } elseif ($all_project) { + $response['data']['warning'] = Project::where('budget_health', 'warning') ->where('company_id', $company_id) ->count(); } else { - $response['data']['warning'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'warning') + $response['data']['warning'] = Project::where('budget_health', 'warning') ->where('created_by_id', $hierarchy) ->count(); } - if ($all_project) { - $response['data']['on-budget'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'on-budget') + if ($role === 'Super Admin') { + Log::info('on-budget'); + $response['data']['on-budget'] = Project::where('budget_health', 'on-budget') + ->count(); + } elseif ($all_project) { + $response['data']['on-budget'] = Project::where('budget_health', 'on-budget') ->where('company_id', $company_id) ->count(); } else { - $response['data']['on-budget'] = Project::where('mulai_proyek', 'like', $year) - ->where('budget_health', 'on-budget') + $response['data']['on-budget'] = Project::where('budget_health', 'on-budget') ->where('created_by_id', $hierarchy) ->count(); } return response()->json($response, 200); } - private function countTotalProjectByBudgetHealthInDivision($divisi, $year, $health) + private function countTotalProjectByBudgetHealthInDivision($divisi, $health) { return Project::where('divisi_id', $divisi) - ->where('mulai_proyek', 'like', $year) /* ->orWhere('akhir_proyek', 'like', $year) */ ->where('budget_health', $health) ->count(); } - public function getTotalProjectBudgetHealthPerDivision($year = '%', $company_id) + public function getTotalProjectBudgetHealthPerDivision($role_name, $company_id) { - $year = $this->interpolateYear($year); - $divisions = Divisi::select('id', 'name') - ->with('children') - ->whereNull('parent') - ->where('company_id', $company_id) - ->get(); + $role = urldecode($role_name); + $divisions = null; + if ($role === 'Super Admin') { + $divisions = Divisi::select('id', 'name') + ->with('children') + ->whereNull('parent') + ->get(); + } else { + $divisions = Divisi::select('id', 'name') + ->with('children') + ->whereNull('parent') + ->where('company_id', $company_id) + ->get(); + } + + // to do : count in more than 1 level child foreach ($divisions as $division) { $budgetData = new Collection(); - $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, $year, 'overrun'), 'overrun'); - $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, $year, 'warning'), 'warning'); - $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, $year, 'on-budget'), 'on-budget'); + $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, 'overrun'), 'overrun'); + $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, 'warning'), 'warning'); + $budgetData->prepend($this->countTotalProjectByBudgetHealthInDivision($division->id, 'on-budget'), 'on-budget'); foreach ($division->children as $d) { - $budgetData['overrun'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, $year, 'overrun'); - $budgetData['warning'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, $year, 'warning'); - $budgetData['on-budget'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, $year, 'on-budget'); + $budgetData['overrun'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, 'overrun'); + $budgetData['warning'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, 'warning'); + $budgetData['on-budget'] += $this->countTotalProjectByBudgetHealthInDivision($d->id, 'on-budget'); } unset($division->children); $division->budgetData = $budgetData; @@ -441,20 +481,28 @@ class DashboardBoDController extends Controller ], 200); } - public function getTotalProjectPerPhase($year = '%', $company_id, $all_project, $hierarchy) + public function getTotalProjectPerPhase($role_name, $company_id, $all_project, $hierarchy) { - $year = $this->interpolateYear($year); - $projectPhases = ProjectPhase::where('company_id', $company_id)->orderBy('order')->get(); + $role = urldecode($role_name); + $projectPhases = null; + if ($role === 'Super Admin') { + $projectPhases = ProjectPhase::orderBy('order')->get(); + } else { + $projectPhases = ProjectPhase::where('company_id', $company_id)->orderBy('order')->get(); + } + + foreach ($projectPhases as $phase) { - if ($all_project) { + if ($role === 'Super Admin') { + $phase->totalProject = Project::where('phase_id', $phase->id) + ->count(); + } elseif ($all_project) { $phase->totalProject = Project::where('phase_id', $phase->id) - ->where('mulai_proyek', 'like', $year) ->where('company_id', $company_id) ->count(); } else { $phase->totalProject = Project::where('phase_id', $phase->id) - ->where('mulai_proyek', 'like', $year) ->where('created_by_id', $hierarchy) ->count(); } @@ -466,29 +514,37 @@ class DashboardBoDController extends Controller ], 200); } - private function countTotalProjectInDivision($id, $year) + private function countTotalProjectInDivision($id) { return Project::where('divisi_id', $id) - ->where('mulai_proyek', 'like', $year) ->count(); } - public function getTotalProjectPerDivision($year = '%', $company_id) + public function getTotalProjectPerDivision($role_name, $company_id) { - $year = $this->interpolateYear($year); + $role = urldecode($role_name); + $divisions = null; + if ($role === 'Super Admin') { + $divisions = Divisi::select('id', 'name', 'parent', 'color') + ->with('children') + ->whereNull('parent') + ->get(); + } else { + $divisions = Divisi::select('id', 'name', 'parent', 'color') + ->with('children') + ->whereNull('parent') + ->where('company_id', $company_id) + ->get(); + } + - $divisions = Divisi::select('id', 'name', 'parent', 'color') - ->with('children') - ->whereNull('parent') - ->where('company_id', $company_id) - ->get(); // to do : count in more than 1 level child foreach ($divisions as $v) { - $v->total = $this->countTotalProjectInDivision($v->id, $year); + $v->total = $this->countTotalProjectInDivision($v->id); foreach ($v->children as $d) { - $v->total += $this->countTotalProjectInDivision($d->id, $year); + $v->total += $this->countTotalProjectInDivision($d->id); } unset($v->children); } @@ -498,30 +554,35 @@ class DashboardBoDController extends Controller ], 200); } - private function countTotalProjectValueInDivision($id, $year) + private function countTotalProjectValueInDivision($id) { return Project::select(DB::raw('SUM(CAST("rencana_biaya" AS DOUBLE PRECISION))')) - ->where('mulai_proyek', 'like', $year) - /* ->orWhere('akhir_proyek', 'like', $year) */ ->where('divisi_id', $id) ->pluck('sum') ->first(); } - public function getTotalProjectValuePerDivision($year = '%', $company_id) + public function getTotalProjectValuePerDivision($role_name, $company_id) { - $year = $this->interpolateYear($year); + $role = urldecode($role_name); + if ($role === 'Super Admin') { + $divisions = Divisi::select('id', 'name', 'color') + ->with('children') + ->whereNull('parent') + ->get(); + } else { + $divisions = Divisi::select('id', 'name', 'color') + ->with('children') + ->whereNull('parent') + ->where('company_id', $company_id) + ->get(); + } - $divisions = Divisi::select('id', 'name', 'color') - ->with('children') - ->whereNull('parent') - ->where('company_id', $company_id) - ->get(); foreach ($divisions as $v) { - $v->total = $this->countTotalProjectValueInDivision($v->id, $year); + $v->total = $this->countTotalProjectValueInDivision($v->id); foreach ($v->children as $d) { - $v->total += $this->countTotalProjectValueInDivision($d->id, $year); + $v->total += $this->countTotalProjectValueInDivision($d->id); } unset($v->children); } diff --git a/routes/web.php b/routes/web.php index 35c97cc..e680928 100644 --- a/routes/web.php +++ b/routes/web.php @@ -23,20 +23,20 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->group(['middleware' => ['auth', 'cors']], function () use ($router) { - $router->get('/dashboard/get-company-cashflow/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure - $router->get('/dashboard/get-invoice-outstanding/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in - $router->get('/dashboard/get-total-project-per-schedule-health/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); - $router->get('/dashboard/get-total-project-per-budget-health/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); - $router->get('/dashboard/get-total-project-schedule-health-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); - $router->get('/dashboard/get-total-project-budget-health-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectBudgetHealthPerDivision'); - $router->get('/dashboard/get-total-project-per-phase/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerPhase'); - $router->get('/dashboard/get-total-project-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectPerDivision'); - $router->get('/dashboard/get-total-project-value-per-division/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getTotalProjectValuePerDivision'); - $router->get('/dashboard/get-detail-expenditure/{year}/{company_id}/{all_project}/{hierarchy}', 'DashboardBoDController@getDetailExpenditure'); - $router->get('/dashboard/get-detail-expenditure-color/{company_id}', 'DashboardBoDController@getDetailExpenditureColor'); - $router->get('/dashboard/get-detail-financial-health-color/{company_id}', 'DashboardBoDController@getDetailFinancialHealthColor'); - $router->get('/dashboard/get-detail-schedule-health-color/{company_id}', 'DashboardBoDController@getDetailScheduleHealthColor'); - $router->get('/dashboard/get-detail-invoice-color/{company_id}', 'DashboardBoDController@getDetailInvoiceColor'); + $router->get('/dashboard/get-company-cashflow/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure + $router->get('/dashboard/get-invoice-outstanding/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getInvoiceOutstanding'); // project invoice vs cash in + $router->get('/dashboard/get-total-project-per-schedule-health/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getTotalProjectPerScheduleHealth'); + $router->get('/dashboard/get-total-project-per-budget-health/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getTotalProjectPerBudgetHealth'); + $router->get('/dashboard/get-total-project-schedule-health-per-division/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getTotalProjectScheduleHealthPerDivision'); + $router->get('/dashboard/get-total-project-budget-health-per-division/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getTotalProjectBudgetHealthPerDivision'); + $router->get('/dashboard/get-total-project-per-phase/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getTotalProjectPerPhase'); + $router->get('/dashboard/get-total-project-per-division/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getTotalProjectPerDivision'); + $router->get('/dashboard/get-total-project-value-per-division/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getTotalProjectValuePerDivision'); + $router->get('/dashboard/get-detail-expenditure/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getDetailExpenditure'); + $router->get('/dashboard/get-detail-expenditure-color/{company_id}/{role_name}', 'DashboardBoDController@getDetailExpenditureColor'); + $router->get('/dashboard/get-detail-financial-health-color/{company_id}/{role_name}', 'DashboardBoDController@getDetailFinancialHealthColor'); + $router->get('/dashboard/get-detail-schedule-health-color/{company_id}/{role_name}', 'DashboardBoDController@getDetailScheduleHealthColor'); + $router->get('/dashboard/get-detail-invoice-color/{company_id}/{role_name}', 'DashboardBoDController@getDetailInvoiceColor'); $router->post('/role/search', 'RoleController@search'); $router->post('/role/add', 'RoleController@add'); From 8d2d5ac78213ace2e06d1ed590821f6be8121079 Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 23 Jan 2024 16:50:25 +0700 Subject: [PATCH 072/155] update select field --- app/Http/Controllers/ProjectController.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 7cf0293..0254307 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -124,8 +124,6 @@ class ProjectController extends Controller 'phase_id', 'calculation_status', 'md.name as divisi_name', - 'nickname', - 'sponsor' ) ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') ->where('m_proyek.id', $id) From a747c1af1d156fa28e2ffc41af3c75d92d7cfa5e Mon Sep 17 00:00:00 2001 From: wahyun Date: Wed, 24 Jan 2024 14:02:26 +0700 Subject: [PATCH 073/155] uplaoded image company --- app/Http/Controllers/ImageController.php | 358 +++++++++++++++-------- routes/web.php | 2 + 2 files changed, 239 insertions(+), 121 deletions(-) diff --git a/app/Http/Controllers/ImageController.php b/app/Http/Controllers/ImageController.php index 6ecb88c..a7b9de5 100644 --- a/app/Http/Controllers/ImageController.php +++ b/app/Http/Controllers/ImageController.php @@ -1,121 +1,237 @@ -hasFile('files')){ - - $this->validate($request, [ - 'ref_id' => 'required', - 'category' => 'required' - ]); - - $ref_id = $request->ref_id; - $dokumen = $request->file('files'); - $extension = $dokumen->extension(); - $name = $ref_id.date("YmdHis").".".$extension; - - $resultMove = $dokumen->move($this->pathImage, $name); - - if($resultMove){ - $data = [ - 'ref_id' => (int)$ref_id, - 'image' => $name, - 'category' => $request->category - ]; - - $result = Image::create($data); - - if($result){ - return response()->json(['status'=>'success', "name_image"=>$name,'message'=>'image upload is successfully!','code'=>200], 200); - }else{ - unlink($this->pathImage.$name); - return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); - } - - }else{ - return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'image is required!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = Image::find($id); - - if($data){ - unlink($this->pathImage.$data->image); - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data image not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data image successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data image failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_image'); - $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 deleteByRef($id, $category) - { - $data = Image::where("ref_id", $id)->where("category", $category)->first(); - - if($data){ - unlink($this->pathImage.$data->image); - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data image not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data image successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data image failed deleted!','code'=>400], 400); - } - } - - public function getByRefId($id, $category) - { - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - if(!$category || $category==""){ - return response()->json(['status'=>'failed','message'=>'category is required!','code'=>400], 400); - die(); - } - - $result = Image::where("ref_id", $id)->where("category", $category)->first(); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data image, please try again later!','code'=>400], 400); - } - } -} +hasFile('files')){ + + $this->validate($request, [ + 'ref_id' => 'required', + 'category' => 'required' + ]); + + $ref_id = $request->ref_id; + $dokumen = $request->file('files'); + $extension = $dokumen->extension(); + $category = $request->category; + $name = $ref_id.date("YmdHis").".".$extension; + + $resultMove = $dokumen->move($this->pathImage, $name); + + if($resultMove){ + $data = [ + 'ref_id' => (int)$ref_id, + 'image' => $name, + 'category' => $category + ]; + + $result = Image::create($data); + + $company = Company::find((int)$ref_id); + if($company && $category === 'company_logo_login') { + $dataArray = json_decode($company['logo_login'], true); + if(isset($dataArray['slider'])) { + $jsonImageSlider['login'] = $name; + $jsonImageSlider['slider'] = $dataArray['slider']; + } else { + $jsonImageSlider['login'] = $name; + } + $company->update([ + 'logo_login' => $jsonImageSlider + ]); + } + + if($company && $category === 'company_logo_header') { + $company->update([ + 'logo_header' => array('content'=>$name) + ]); + } + + if($company && $category === 'company_favicon') { + $company->update([ + 'favicon_image' => array('content'=>$name) + ]); + } + + if($result){ + return response()->json(['status'=>'success', "name_image"=>$name,'message'=>'image upload is successfully!','code'=>200], 200); + }else{ + unlink($this->pathImage.$name); + return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); + } + + }else{ + return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); + } + }else{ + return response()->json(['status'=>'failed','message'=>'image is required!','code'=>400], 400); + } + } + + public function uploadMultipleImage(Request $request) { + $this->validate($request, [ + 'ref_id' => 'required', + 'category' => 'required', + 'files.*' => 'required|file|mimes:jpeg,png,jpg,gif|max:2048', + ]); + + if ($request->hasFile('files')) { + $ref_id = $request->ref_id; + $category = $request->category; + $dokumen = $request->file('files'); + $successCount = 0; + $imageSlider = []; + foreach ($dokumen as $file) { + $extension = $file->extension(); + $name = $ref_id.date("YmdHis").$successCount.".".$extension; + + $resultMove = $file->move($this->pathImage, $name); + + if ($resultMove) { + $data = [ + 'ref_id' => (int) $ref_id, + 'image' => $name, + 'category' => $category + ]; + $imageSlider[] = [ + 'content' => $name + ]; + $result = Image::create($data); + if ($result) { + $successCount++; + } else { + unlink($this->pathImage . $name); + } + } + } + $company = Company::find((int)$ref_id); + if($company && $category === 'company_slider_login') { + $dataArray = json_decode($company['logo_login'], true); + if(isset($dataArray['login'])) { + $jsonImageSlider['login'] = $dataArray['login']; + $jsonImageSlider['slider'] = $imageSlider; + } else { + $jsonImageSlider['slider'] = $imageSlider; + } + $company->update([ + 'logo_login' => $jsonImageSlider + ]); + } + if ($successCount > 0 && $company) { + return response()->json(['status' => 'success', 'message' => "$successCount images uploaded successfully!", 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'No images uploaded successfully!', 'code' => 400], 400); + } + } else { + return response()->json(['status' => 'failed', 'message' => 'Image is required!', 'code' => 400], 400); + } + } + + + + public function delete($id) + { + $data = Image::find($id); + + if($data){ + unlink($this->pathImage.$data->image); + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data image not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data image successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data image failed deleted!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_image'); + $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 deleteByRef($id, $category) + { + $data = Image::where("ref_id", intval($id))->where("category", $category)->first(); + + if($data){ + unlink($this->pathImage.$data->image); + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data image not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data image successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data image failed deleted!','code'=>400], 400); + } + } + + public function deleteByRefMultiple($id, $category) + { + $successCount = 0; + $data = Image::where([ + ["ref_id", intval($id)], + ["category", $category] + ])->get(); + if($data->isNotEmpty()) { + foreach($data as $img) { + unlink($this->pathImage.$img->image); + $delete = $img->delete(); + if($delete){ + $successCount++; + } + } + } else { + return response()->json(['status'=>'failed','message'=>'data image not found!','code'=>400], 400); + die(); + } + + if($successCount > 0) { + return response()->json(['status'=>'success','message'=>'data image successfully deleted!','code'=>200], 200); + } else { + return response()->json(['status'=>'failed','message'=>'data image failed deleted!','code'=>400], 400); + } + } + + public function getByRefId($id, $category) + { + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + if(!$category || $category==""){ + return response()->json(['status'=>'failed','message'=>'category is required!','code'=>400], 400); + die(); + } + + $result = Image::where("ref_id", $id)->where("category", $category)->first(); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data image, please try again later!','code'=>400], 400); + } + } +} diff --git a/routes/web.php b/routes/web.php index 35c97cc..85251b2 100644 --- a/routes/web.php +++ b/routes/web.php @@ -312,7 +312,9 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/image/search', 'ImageController@search'); $router->delete('/image/delete/{id}', 'ImageController@delete'); $router->delete('/image/delete/{id}/{category}', 'ImageController@deleteByRef'); + $router->delete('/image/multiple-delete/{id}/{category}', 'ImageController@deleteByRefMultiple'); $router->post('/image/upload', 'ImageController@uploadImage'); + $router->post('/image/multiple-upload', 'ImageController@uploadMultipleImage'); $router->get('/image/{id}/{category}', 'ImageController@getByRefId'); $router->post('/panic-button/add', 'PanicButtonController@add'); From 7724402dfe33223bfe3d0dbdb4a69bb95add8507 Mon Sep 17 00:00:00 2001 From: farhantock Date: Sun, 28 Jan 2024 18:06:52 +0700 Subject: [PATCH 074/155] update filter datatables --- .../Controllers/AssignMaterialController.php | 147 ++++++++++-------- 1 file changed, 80 insertions(+), 67 deletions(-) diff --git a/app/Http/Controllers/AssignMaterialController.php b/app/Http/Controllers/AssignMaterialController.php index 0d7b303..e385a95 100644 --- a/app/Http/Controllers/AssignMaterialController.php +++ b/app/Http/Controllers/AssignMaterialController.php @@ -12,13 +12,15 @@ use Datatables; class AssignMaterialController extends Controller { - private function sanitizeDecimal($number) { - $number = str_replace(".","",$number); - $number = str_replace(",",".",$number); + private function sanitizeDecimal($number) + { + $number = str_replace(".", "", $number); + $number = str_replace(",", ".", $number); return $number; } - public function add(Request $request){ + public function add(Request $request) + { $this->validate($request, [ 'activity_id' => 'required', 'material_id' => 'required', @@ -29,8 +31,8 @@ class AssignMaterialController extends Controller $checkStock = RequestMaterial::where("id", $request->material_id)->first(); $currentStock = $checkStock->qty; - if((int)$currentStock < (int)$request->qty_planning){ - return response()->json(['status'=>'failed','message'=>'Stock is not enough!','code'=> 500]); + if ((int)$currentStock < (int)$request->qty_planning) { + return response()->json(['status' => 'failed', 'message' => 'Stock is not enough!', 'code' => 500]); } $start_date = $activity->start_date; @@ -43,56 +45,58 @@ class AssignMaterialController extends Controller $data['budget'] = $checkStock->price; $data['qty_planning'] = $this->sanitizeDecimal($data['qty_planning']); - if ($planDate >= $startDate) { + if ($planDate >= $startDate) { $result = AssignMaterial::create($data); - return response()->json(['status'=>'success','message'=>'Data added!', 'code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 400], 400); + return response()->json(['status' => 'success', 'message' => 'Data added!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Failed to add data!', 'code' => 400], 400); } } - 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); + 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); + 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); + 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); + return response()->json(['status' => 'failed', 'message' => 'Failed to update!', 'code' => 500], 500); } public function delete($id) { $data = AssignMaterial::where('id', $id)->first(); - $reports = ReportActivityMaterial::where('assign_material_id', $data->id)->get(); - if (isset($reports)) { + $reports = ReportActivityMaterial::where('assign_material_id', $data->id)->get(); + if (isset($reports)) { foreach ($reports as $report) { $report->delete(); } - } + } - if($data->delete()) - return response()->json(['status'=>'success','message'=>'Data deleted!','code'=> 200], 200); + 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); + 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); + 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); + if ($result) + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); } public function search(Request $request) @@ -103,7 +107,7 @@ class AssignMaterialController extends Controller $countBuilder = $dataBuilder['count']; $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } public function list() @@ -111,18 +115,21 @@ class AssignMaterialController extends Controller $data = AssignMaterial::all(); $countData = $data->count(); - if($data) - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + 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); + return response()->json(['status' => 'failed', 'message' => 'Failed to get the data!', 'code' => 500], 500); } - public function datatables(Request $request){ + public function datatables(Request $request) + { $id_activity = $request->query('idact'); $type = $request->query('type') ?? "material"; $data = AssignMaterial::select( - "assign_material_to_activity.*","m.description as material_name", "m.uom as uom" - ) + "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) ->where('assign_material_to_activity.type', $type) @@ -130,28 +137,33 @@ class AssignMaterialController extends Controller ->get(); return Datatables::of($data) ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; + ->addColumn('action', function ($row) { + $actionBtn = ''; return $actionBtn; }) ->rawColumns(['action'])->make(true); } - public function datatablesForReportActivity(Request $request){ + public function datatablesForReportActivity(Request $request) + { $id_activity = $request->query('idact'); - $data = - AssignMaterial::select( - DB::raw('(SELECT SUM(assign_material_to_activity.qty_planning) FROM assign_material_to_activity WHERE assign_material_to_activity.activity_id = ram.activity_id) as qty_planning'), - DB::raw('SUM(ram.qty) as qty_sum'), - "m.description as material_name", - "assign_material_to_activity.activity_id", - ) - ->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") + $query = AssignMaterial::select( + DB::raw('(SELECT SUM(assign_material_to_activity.qty_planning) FROM assign_material_to_activity WHERE assign_material_to_activity.activity_id = ram.activity_id) as qty_planning'), + DB::raw('SUM(ram.qty) as qty_sum'), + "m.description as material_name", + "assign_material_to_activity.activity_id" + ) + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id"); + if (!AssignMaterial::join("report_activity_material as ram", "ram.assign_material_id", "=", "assign_material_to_activity.id")->where("assign_material_to_activity.activity_id", $id_activity)->exists()) { + $query->leftJoin("report_activity_material as ram", "ram.assign_material_id", "=", "assign_material_to_activity.id"); + } else { + $query->join("report_activity_material as ram", "ram.assign_material_id", "=", "assign_material_to_activity.id"); + } + $data = $query->groupBy("m.description") ->groupBy("ram.activity_id") ->groupBy("assign_material_to_activity.activity_id") - ->where("assign_material_to_activity.activity_id", $id_activity)->get(); + ->where("assign_material_to_activity.activity_id", $id_activity) + ->get(); return Datatables::of($data) ->addIndexColumn() // ->addColumn('qty_planning', function($row){ @@ -164,60 +176,61 @@ class AssignMaterialController extends Controller // ->where("ram.activity_id", $row->activity_id)->first(); // return $val_qty_act ? $val_qty_act->qty_sum : '-'; // }) - ->addColumn('status_activity', function($row){ + ->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){ + ->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){ + ->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){ + ->addColumn('uom', function ($row) { $val_uom = RequestMaterial::select("uom") ->where('description', '=', $row->material_name)->first(); return $val_uom ? $val_uom->uom : null; }) - ->addColumn('assign_material_id', function($row){ - $assignMaterial =AssignMaterial::select('assign_material_to_activity.id')->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->where('activity_id', $row->activity_id)->where('m.description', $row->material_name)->first(); + ->addColumn('assign_material_id', function ($row) { + $assignMaterial = AssignMaterial::select('assign_material_to_activity.id')->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->where('activity_id', $row->activity_id)->where('m.description', $row->material_name)->first(); return $assignMaterial ? $assignMaterial->id : null; }) - ->addColumn('action', function($row){ + ->addColumn('action', function ($row) { $dataPlan = AssignMaterial::select('assign_material_to_activity.id')->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") ->where('activity_id', $row->activity_id)->where('m.description', $row->material_name)->first(); - $actionBtn = ''; - $actionBtn .= ''; + $actionBtn = ''; + $actionBtn .= ''; return $actionBtn; }) ->rawColumns(['action'])->make(true); } - public function ForReportActivityByMaterial(Request $request){ + 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") + $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) { $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); + 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 0884009bdd0641a9807832f1cee6c5fbcf3de679 Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 30 Jan 2024 13:13:37 +0700 Subject: [PATCH 075/155] update response appConfig --- app/Http/Controllers/AuthController.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 78fda02..1f26ba3 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -61,6 +61,14 @@ class AuthController extends Controller $dataRole = Role::find($user->role_id); $dataHierarchy = $this->getDataHierarchy($user->divisi_id, $user->id); $configApp = Company::where('id', $user->company_id)->first(); + if ($configApp) { + $logoLogin = json_decode($configApp->logo_login, true); + $favicon = json_decode($configApp->favicon_image, true); + $logoHeader = json_decode($configApp->logo_header, true); + $configApp->logo_login = $logoLogin; + $configApp->favicon_image = $favicon; + $configApp->logo_header = $logoHeader; + } if ($configApp) $user->configApp = $configApp; From 3e5692847b0c3423e9e11eedf36698554668e3da Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 30 Jan 2024 14:54:18 +0700 Subject: [PATCH 076/155] Demo End Point --- app/Http/Controllers/DemoController.php | 114 ++++++++++++++++++++++++ app/Models/Demo.php | 27 ++++++ routes/web.php | 11 ++- 3 files changed, 150 insertions(+), 2 deletions(-) create mode 100644 app/Http/Controllers/DemoController.php create mode 100644 app/Models/Demo.php diff --git a/app/Http/Controllers/DemoController.php b/app/Http/Controllers/DemoController.php new file mode 100644 index 0000000..715f379 --- /dev/null +++ b/app/Http/Controllers/DemoController.php @@ -0,0 +1,114 @@ +validate($request, [ + 'name' => 'required', + 'role' => 'required', + 'number_phone' => 'required', + 'message' => 'required', + ]); + + $data = $request->all(); + + $data['created_by'] = '@System'; + $data['status'] = 'New Request'; + + $result = Demo::create($data); + + if ($result) { + return response()->json(['status' => 'success', 'data' => $result, 'message' => 'Request Demo successfully!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Request Demo 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 = Demo::find($id); + + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get data Demo, 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 = Demo::find($id); + + + if ($data) { + $result = $data->update($request->all()); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Demo not found!', 'code' => 400], 400); + die(); + } + + + if ($result) { + return response()->json(['status' => 'success', 'message' => 'data Demo successfully updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Demo failed updated!', 'code' => 400], 400); + } + } + + public function delete($id) + { + $data = Demo::find($id); + + if ($data) { + $delete = $data->delete(); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Demo not found!', 'code' => 400], 400); + die(); + } + + + if ($delete) { + return response()->json(['status' => 'success', 'message' => 'data Demo successfully deleted!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Demo failed deleted!', 'code' => 400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_company'); + $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 = Demo::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 Demo, please try again later!', 'code' => 400], 400); + } + } +} diff --git a/app/Models/Demo.php b/app/Models/Demo.php new file mode 100644 index 0000000..ded3b3a --- /dev/null +++ b/app/Models/Demo.php @@ -0,0 +1,27 @@ +group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/image/search', 'ImageController@search'); $router->delete('/image/delete/{id}', 'ImageController@delete'); $router->delete('/image/delete/{id}/{category}', 'ImageController@deleteByRef'); - $router->delete('/image/multiple-delete/{id}/{category}', 'ImageController@deleteByRefMultiple'); + $router->delete('/image/multiple-delete/{id}/{category}', 'ImageController@deleteByRefMultiple'); $router->post('/image/upload', 'ImageController@uploadImage'); - $router->post('/image/multiple-upload', 'ImageController@uploadMultipleImage'); + $router->post('/image/multiple-upload', 'ImageController@uploadMultipleImage'); $router->get('/image/{id}/{category}', 'ImageController@getByRefId'); $router->post('/panic-button/add', 'PanicButtonController@add'); @@ -550,5 +550,12 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/menu-company/search', 'MenuCompanyController@search'); $router->get('/menu-company/management/{id}', 'MenuCompanyController@listMenu'); $router->get('/menu-company/list', 'MenuCompanyController@list'); + + $router->post('/demo-management/add', 'DemoController@add'); + $router->get('/demo-management/edit/{id}', 'DemoController@edit'); + $router->put('/demo-management/update/{id}', 'DemoController@update'); + $router->post('/demo-management/search', 'DemoController@search'); + $router->delete('/demo-management/delete/{id}', 'DemoController@delete'); + $router->get('/demo-management/list', 'DemoController@list'); }); }); From 1e1388f46d0cb15402e4e141f3b95af09a60534e Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 30 Jan 2024 15:03:58 +0700 Subject: [PATCH 077/155] update demo controller --- app/Http/Controllers/DemoController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/DemoController.php b/app/Http/Controllers/DemoController.php index 715f379..a0bda60 100644 --- a/app/Http/Controllers/DemoController.php +++ b/app/Http/Controllers/DemoController.php @@ -5,7 +5,7 @@ namespace App\Http\Controllers; use App\Models\Demo; use Illuminate\Http\Request; -class CompanyController extends Controller +class DemoController extends Controller { public function add(Request $request) { @@ -92,7 +92,7 @@ class CompanyController extends Controller public function search(Request $request) { $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_company'); + $dataBuilder = $this->setUpPayload($payload, 'm_demo'); $builder = $dataBuilder['builder']; $countBuilder = $dataBuilder['count']; $dataGet = $builder->get(); From b005fbbcae9ff3351121215af661dbb3f2456ac9 Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 30 Jan 2024 17:45:16 +0700 Subject: [PATCH 078/155] send email register --- app/Http/Controllers/AuthController.php | 65 ++++++++++++++++++++++++- routes/web.php | 1 + 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 1f26ba3..e88d853 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -13,7 +13,7 @@ use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Password; use Illuminate\Validation\ValidationException; - +const URL_EMAIL = 'https://notifapp.odm-iu.com/service-mail/notif_mail.php'; class AuthController extends Controller { public function __construct() @@ -108,4 +108,67 @@ class AuthController extends Controller return response()->json(['code' => 201, 'message' => "username doesn't match"], 201); } } + + + public function sendEmail(Request $request) + { + $hashed = Str::random(15); + $email = $request->email; + $user = User::select('email', 'name')->where('email', $email)->first(); + + if (!$user) { + return response()->json(['status' => 'error', 'message' => 'e-mail not found '], 400); + } else { + $this->reqHttpCurl($email, $hashed, $user->username, $user->name); + // $updateUser = User::where('email', $email)->update(['password'=> $hashed]); + if (User::where('email', $email)->update(['password' => md5($hashed)])) + return response()->json(['status' => 'success', 'code' => 200, 'message' => 'Password already sent to mail'], 200); + + return response()->json(['status' => 'error', 'code' => 400, 'message' => 'e-mail not found '], 400); + } + } + + private function reqHttpCurl($email, $password, $username, $name) + { + $postData = [ + "to" => $email, + "username" => $name, + "username" => $username, + "password" => $password, + "from" => "app.integrasia@integrasiautama.com", + "alias_from" => "OSPRO", + "subject" => "Registration OSPRO", + "body" => "registration-ospro" + ]; + + $curl = curl_init(); + + curl_setopt_array($curl, array( + CURLOPT_URL => URL_EMAIL, // your preferred url + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30000, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode($postData), + CURLOPT_HTTPHEADER => array( + // Set here requred headers + "accept: */*", + "accept-language: en-US,en;q=0.8", + "content-type: application/json", + ), + )); + + $response = curl_exec($curl); + $err = curl_error($curl); + + curl_close($curl); + + if ($err) { + echo "cURL Error #:" . $err; + } else { + print_r(json_decode($response)); + } + } } diff --git a/routes/web.php b/routes/web.php index cd1d199..3c8bdb6 100644 --- a/routes/web.php +++ b/routes/web.php @@ -6,6 +6,7 @@ $router->get('/', function () use ($router) { $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($router) { $router->post('/login', 'AuthController@login'); + $router->post('/send-email', 'AuthController@sendEmail'); $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); From 522fd9ba940998d1e94797cbc0997375c8b225eb Mon Sep 17 00:00:00 2001 From: wahyun Date: Wed, 31 Jan 2024 10:39:26 +0700 Subject: [PATCH 079/155] update compro endpoint --- app/Http/Controllers/AuthController.php | 207 +++++++++--------- .../Controllers/HumanResourceController.php | 94 +++++++- .../Controllers/ScheduleDemoController.php | 32 +++ app/Models/Company.php | 1 + app/Models/Demo.php | 26 +++ app/Models/HumanResource.php | 1 + routes/web.php | 6 + 7 files changed, 263 insertions(+), 104 deletions(-) create mode 100644 app/Http/Controllers/ScheduleDemoController.php create mode 100644 app/Models/Demo.php diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 78fda02..f650e8d 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -1,103 +1,104 @@ -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); - - $usernameCheck = false; - $passwordCheck = false; - - if (User::where('username', $username)->exists()) - $usernameCheck = true; - - if (User::where('password', md5($password))->exists()) - $passwordCheck = true; - - if ($usernameCheck & $passwordCheck) { - $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); - - $dataUpdateFcm = array( - "fcm_token" => $fcm_token - ); - - $hr = User::find($user->id); - - if ($hr) - $hr->update($dataUpdateFcm); - } - - $dataRole = Role::find($user->role_id); - $dataHierarchy = $this->getDataHierarchy($user->divisi_id, $user->id); - $configApp = Company::where('id', $user->company_id)->first(); - - if ($configApp) - $user->configApp = $configApp; - - if ($dataRole) - $user->role = $dataRole; - - if ($dataHierarchy) - $user->hierarchy = $dataHierarchy; - - if (!$token = Auth::login($user)) - return response()->json(['error' => 'Unauthorized'], 401); - - $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( - 'data_user' => $user, - 'access_token' => $token, - 'token_type' => 'bearer', - 'expires_in' => auth()->factory()->getTTL() * $ttl, - ), - ]); - } else { - if (!$usernameCheck && !$passwordCheck) - return response()->json(['code' => 201, 'message' => "username and password doesn't match"], 201); - if (!$passwordCheck) - return response()->json(['code' => 201, 'message' => "password doesn't match"], 201); - if (!$usernameCheck) - return response()->json(['code' => 201, 'message' => "username doesn't match"], 201); - } - } -} +middleware('auth:api', ['except' => ['login']]); + } + + public function login(Request $request) + { + $username = $request->username; + $email = $request->email; + $password = $request->password; + $remember = $request->remember; + $is_mobile = $request->is_mobile; + + if (empty($email) && empty($username) || empty($password)) + return response()->json(['status' => 'error', 'message' => 'You must fill all the fields'], 400); + + $usernameCheck = false; + $passwordCheck = false; + + if (User::where('username', $username)->orWhere('email', $email)->exists()) + $usernameCheck = true; + + if (User::where('password', md5($password))->exists()) + $passwordCheck = true; + + if ($usernameCheck & $passwordCheck) { + $user = User::where('username', $username)->where('password', md5($password))->orWhere('email', $email)->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); + + $dataUpdateFcm = array( + "fcm_token" => $fcm_token + ); + + $hr = User::find($user->id); + + if ($hr) + $hr->update($dataUpdateFcm); + } + + $dataRole = Role::find($user->role_id); + $dataHierarchy = $this->getDataHierarchy($user->divisi_id, $user->id); + $configApp = Company::where('id', $user->company_id)->first(); + + if ($configApp) + $user->configApp = $configApp; + + if ($dataRole) + $user->role = $dataRole; + + if ($dataHierarchy) + $user->hierarchy = $dataHierarchy; + + if (!$token = Auth::login($user)) + return response()->json(['error' => 'Unauthorized'], 401); + + $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( + 'data_user' => $user, + 'access_token' => $token, + 'token_type' => 'bearer', + 'expires_in' => auth()->factory()->getTTL() * $ttl, + ), + ]); + } else { + if (!$usernameCheck && !$passwordCheck) + return response()->json(['code' => 201, 'message' => "username and password doesn't match"], 201); + if (!$passwordCheck) + return response()->json(['code' => 201, 'message' => "password doesn't match"], 201); + if (!$usernameCheck) + return response()->json(['code' => 201, 'message' => "username doesn't match"], 201); + } + } +} diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index 6c78f6c..a10877f 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -2,12 +2,16 @@ namespace App\Http\Controllers; +use App\Models\User; +use Illuminate\Support\Str; +use App\Models\UserToProyek; use Illuminate\Http\Request; use App\Models\HumanResource; use App\Models\UserToActivity; -use App\Models\UserToProyek; use Illuminate\Support\Facades\Artisan; +const URL_EMAIL = 'https://notifapp.odm-iu.com/service-mail/notif_mail.php'; + class HumanResourceController extends Controller { public function add(Request $request) @@ -35,6 +39,34 @@ class HumanResourceController extends Controller } } + public function add_user(Request $request) + { + $this->validate($request, [ + 'role_id' => 'required', + 'name' => 'required', + 'ktp_number' => 'required|numeric|unique:m_users,ktp_number', + 'employee_type' => 'required', + 'company_id' => 'required', + 'username' => 'required', + 'email' => 'required' + ]); + + $data = $request->all(); + + if (isset($request->password) && $request->password != "") { + $data['password'] = md5($request->password); + } + + $result = HumanResource::create($data); + + if ($result) { + $this->sendEmail($request->email, $data['password']); + return response()->json(['status' => 'success', 'message' => 'Human Resource Pool successfull created', 'code' => 200]); + } else { + return response()->json(['status' => 'failed', 'message' => 'Human Resource Pool failed created', 'code' => 400]); + } + } + public function edit($id) { if (!$id || (int) $id < 0 || $id == "") { @@ -197,4 +229,64 @@ class HumanResourceController extends Controller { Artisan::call('sync:integration-human-resources'); } + + public function sendEmail($email, $hashPassword) + { + $hashed = $hashPassword; + $user = User::select('email', 'name')->where('email', $email)->first(); + + if (!$user) { + return response()->json(['status' => 'error', 'message' => 'e-mail not found '], 400); + } else { + $this->reqHttpCurl($email, $hashed, $user->name); + // if (User::where('email', $email)->update(['password'=> md5($hashed)])) + // return response()->json(['status' => 'success', 'code'=>200, 'message' => 'Password already sent to mail'], 200); + + return response()->json(['status' => 'error', 'code'=>400, 'message' => 'e-mail not found '], 400); + } + } + + private function reqHttpCurl($email, $password, $username) + { + $postData = [ + "to" => $email, + "password"=> $password, + "name" => $username, + "from" => "app.integrasia@integrasiautama.com", + "alias_from" => "ADW", + "subject" => "Informasi Akun", + "body" => "informasi-akun-adw" + ]; + + $curl = curl_init(); + + curl_setopt_array($curl, array( + CURLOPT_URL => URL_EMAIL, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30000, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode($postData), + CURLOPT_HTTPHEADER => array( + // Set here requred headers + "accept: */*", + "accept-language: en-US,en;q=0.8", + "content-type: application/json", + ), + )); + + $response = curl_exec($curl); + $err = curl_error($curl); + + curl_close($curl); + + if ($err) { + echo "cURL Error #:" . $err; + } else { + print_r(json_decode($response)); + } + + } } diff --git a/app/Http/Controllers/ScheduleDemoController.php b/app/Http/Controllers/ScheduleDemoController.php new file mode 100644 index 0000000..f3a5130 --- /dev/null +++ b/app/Http/Controllers/ScheduleDemoController.php @@ -0,0 +1,32 @@ +validate($request, [ + 'name' => 'required', + 'role' => 'required', + 'email' => 'required', + 'number_phone' => 'required', + 'status' => 'required', + 'message' => 'required' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + $result = Demo::create($data); + + if ($result) { + return response()->json(['status' => 'success','data' => $result, 'message' => 'add schedule successfully!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'add data schedule failed!', 'code' => 400], 400); + } + } +} diff --git a/app/Models/Company.php b/app/Models/Company.php index 7593aed..403c27d 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -32,6 +32,7 @@ class Company extends Model 'created_by', 'updated_at', 'updated_by', + 'cluster', 'date_register' ]; } diff --git a/app/Models/Demo.php b/app/Models/Demo.php new file mode 100644 index 0000000..7b1f0a1 --- /dev/null +++ b/app/Models/Demo.php @@ -0,0 +1,26 @@ +get('/', function () use ($router) { $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($router) { $router->post('/login', 'AuthController@login'); + $router->post('/company-management-user/add', 'CompanyController@add'); + $router->post('/company-management-user/search', 'CompanyController@search'); + $router->post('/human-resource-user/add', 'HumanResourceController@add_user'); + $router->get('/company-management-user/edit/{id}', 'CompanyController@edit'); + $router->post('/schedule-demo/add','ScheduleDemoController@add'); + $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); $router->put('/menu/update/{id}', 'MenuController@update'); From 5e0e4ad0f6c59b679207b72e621450de5b9b891d Mon Sep 17 00:00:00 2001 From: wahyun Date: Wed, 31 Jan 2024 11:25:42 +0700 Subject: [PATCH 080/155] update conflict --- app/Http/Controllers/DemoController.php | 4 ++- .../Controllers/ScheduleDemoController.php | 32 ------------------- routes/web.php | 2 +- 3 files changed, 4 insertions(+), 34 deletions(-) delete mode 100644 app/Http/Controllers/ScheduleDemoController.php diff --git a/app/Http/Controllers/DemoController.php b/app/Http/Controllers/DemoController.php index a0bda60..3e44c29 100644 --- a/app/Http/Controllers/DemoController.php +++ b/app/Http/Controllers/DemoController.php @@ -12,8 +12,10 @@ class DemoController extends Controller $this->validate($request, [ 'name' => 'required', 'role' => 'required', + 'email' => 'required', 'number_phone' => 'required', - 'message' => 'required', + 'status' => 'required', + 'message' => 'required' ]); $data = $request->all(); diff --git a/app/Http/Controllers/ScheduleDemoController.php b/app/Http/Controllers/ScheduleDemoController.php deleted file mode 100644 index f3a5130..0000000 --- a/app/Http/Controllers/ScheduleDemoController.php +++ /dev/null @@ -1,32 +0,0 @@ -validate($request, [ - 'name' => 'required', - 'role' => 'required', - 'email' => 'required', - 'number_phone' => 'required', - 'status' => 'required', - 'message' => 'required' - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - $result = Demo::create($data); - - if ($result) { - return response()->json(['status' => 'success','data' => $result, 'message' => 'add schedule successfully!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'add data schedule failed!', 'code' => 400], 400); - } - } -} diff --git a/routes/web.php b/routes/web.php index 31882d2..c40d8e9 100644 --- a/routes/web.php +++ b/routes/web.php @@ -12,7 +12,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/company-management-user/search', 'CompanyController@search'); $router->post('/human-resource-user/add', 'HumanResourceController@add_user'); $router->get('/company-management-user/edit/{id}', 'CompanyController@edit'); - $router->post('/schedule-demo/add','ScheduleDemoController@add'); + $router->post('/demo-management-user/add', 'DemoController@add'); $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); From b5b94e58ba38e3b7714db83adf0264e44751bcba Mon Sep 17 00:00:00 2001 From: wahyun Date: Thu, 1 Feb 2024 11:45:26 +0700 Subject: [PATCH 081/155] finish register & email notif --- .../Controllers/HumanResourceController.php | 32 ++++++++----------- app/Http/Controllers/RoleController.php | 2 +- routes/web.php | 4 ++- 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index a10877f..2ea52d7 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -19,7 +19,7 @@ class HumanResourceController extends Controller $this->validate($request, [ 'role_id' => 'required', 'name' => 'required', - 'ktp_number' => 'required|numeric|unique:m_users,ktp_number', + 'ktp_number' => 'required|string|unique:m_users,ktp_number', 'employee_type' => 'required', 'company_id' => 'required' ]); @@ -44,7 +44,7 @@ class HumanResourceController extends Controller $this->validate($request, [ 'role_id' => 'required', 'name' => 'required', - 'ktp_number' => 'required|numeric|unique:m_users,ktp_number', + 'ktp_number' => 'required|string|unique:m_users,ktp_number', 'employee_type' => 'required', 'company_id' => 'required', 'username' => 'required', @@ -60,7 +60,7 @@ class HumanResourceController extends Controller $result = HumanResource::create($data); if ($result) { - $this->sendEmail($request->email, $data['password']); + $this->sendEmail($request->email, $request->password); return response()->json(['status' => 'success', 'message' => 'Human Resource Pool successfull created', 'code' => 200]); } else { return response()->json(['status' => 'failed', 'message' => 'Human Resource Pool failed created', 'code' => 400]); @@ -91,7 +91,7 @@ class HumanResourceController extends Controller } $humanresource = HumanResource::find($id); - $request->ktp_number !== $humanresource['ktp_number'] ? $this->validate($request,['ktp_number'=>'unique:m_users,ktp_number|numeric']) : ''; + $request->ktp_number !== $humanresource['ktp_number'] ? $this->validate($request,['ktp_number'=>'unique:m_users,ktp_number|string']) : ''; $request->email !== $humanresource['email'] ? $this->validate($request,['email'=>'unique:m_users,email|email']) : ''; $request->password ? $this->validate($request,['password'=>'required|min:8']) : ''; @@ -230,32 +230,28 @@ class HumanResourceController extends Controller Artisan::call('sync:integration-human-resources'); } - public function sendEmail($email, $hashPassword) + public function sendEmail($email, $password) { - $hashed = $hashPassword; - $user = User::select('email', 'name')->where('email', $email)->first(); - + $user = User::select('email', 'name', 'username')->where('email', $email)->first(); if (!$user) { return response()->json(['status' => 'error', 'message' => 'e-mail not found '], 400); } else { - $this->reqHttpCurl($email, $hashed, $user->name); - // if (User::where('email', $email)->update(['password'=> md5($hashed)])) - // return response()->json(['status' => 'success', 'code'=>200, 'message' => 'Password already sent to mail'], 200); - + $this->reqHttpCurl($email, $password, $user->username, $user->name); return response()->json(['status' => 'error', 'code'=>400, 'message' => 'e-mail not found '], 400); } } - private function reqHttpCurl($email, $password, $username) + private function reqHttpCurl($email, $password, $username, $name) { $postData = [ "to" => $email, - "password"=> $password, - "name" => $username, + "name" => $name, + "username" => $username, + "password" => $password, "from" => "app.integrasia@integrasiautama.com", - "alias_from" => "ADW", - "subject" => "Informasi Akun", - "body" => "informasi-akun-adw" + "alias_from" => "OSPRO", + "subject" => "Registration OSPRO", + "body" => "registration-ospro" ]; $curl = curl_init(); diff --git a/app/Http/Controllers/RoleController.php b/app/Http/Controllers/RoleController.php index 9b1c8b5..371ba5c 100644 --- a/app/Http/Controllers/RoleController.php +++ b/app/Http/Controllers/RoleController.php @@ -28,7 +28,7 @@ class RoleController extends Controller 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); + return response()->json(['status' => 'success', 'data' => $result, 'message' => 'Data added!', 'code' => 200], 200); } public function edit($id) diff --git a/routes/web.php b/routes/web.php index c40d8e9..69147fb 100644 --- a/routes/web.php +++ b/routes/web.php @@ -6,13 +6,15 @@ $router->get('/', function () use ($router) { $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($router) { $router->post('/login', 'AuthController@login'); + // Landing Route $router->post('/send-email', 'AuthController@sendEmail'); - $router->post('/company-management-user/add', 'CompanyController@add'); $router->post('/company-management-user/search', 'CompanyController@search'); $router->post('/human-resource-user/add', 'HumanResourceController@add_user'); $router->get('/company-management-user/edit/{id}', 'CompanyController@edit'); $router->post('/demo-management-user/add', 'DemoController@add'); + $router->post('/role-user/add', 'RoleController@add'); + $router->post('/menu-company-user/add-multiple', 'MenuCompanyController@addMultiple'); $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); From c189f294fc969f8bc2bd006efdb52a3346bcb70b Mon Sep 17 00:00:00 2001 From: wahyun Date: Fri, 2 Feb 2024 16:33:49 +0700 Subject: [PATCH 082/155] authcontroller forgot password --- app/Http/Controllers/AuthController.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 810f722..53d34f4 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -2,14 +2,15 @@ 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; +use App\Models\User; use App\Models\Company; + +use Illuminate\Support\Str; +use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Password; use Illuminate\Validation\ValidationException; @@ -18,7 +19,7 @@ class AuthController extends Controller { public function __construct() { - $this->middleware('auth:api', ['except' => ['login']]); + $this->middleware('auth:api', ['except' => ['login','sendEmail']]); } public function login(Request $request) @@ -114,13 +115,12 @@ class AuthController extends Controller { $hashed = Str::random(15); $email = $request->email; - $user = User::select('email', 'name')->where('email', $email)->first(); + $user = User::select('email', 'name', 'username')->where('email', $email)->first(); - if (!$user) { + if (!$user || empty($email)) { return response()->json(['status' => 'error', 'message' => 'e-mail not found '], 400); } else { $this->reqHttpCurl($email, $hashed, $user->username, $user->name); - // $updateUser = User::where('email', $email)->update(['password'=> $hashed]); if (User::where('email', $email)->update(['password' => md5($hashed)])) return response()->json(['status' => 'success', 'code' => 200, 'message' => 'Password already sent to mail'], 200); From cc8b2cf1f7bb61a91faa30e914d7e696cb77a597 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 6 Feb 2024 12:52:39 +0700 Subject: [PATCH 083/155] update method sendEmail --- app/Http/Controllers/AuthController.php | 31 ++++++++++++++++++------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 53d34f4..4f06657 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -113,18 +113,33 @@ class AuthController extends Controller public function sendEmail(Request $request) { - $hashed = Str::random(15); + if (empty($request->password)) { + $hashed = Str::random(15); + } else { + $hashed = $request->password; + } + $email = $request->email; $user = User::select('email', 'name', 'username')->where('email', $email)->first(); if (!$user || empty($email)) { - return response()->json(['status' => 'error', 'message' => 'e-mail not found '], 400); + return response()->json(['status' => 'error', 'message' => 'e-mail not found'], 400); } else { - $this->reqHttpCurl($email, $hashed, $user->username, $user->name); - if (User::where('email', $email)->update(['password' => md5($hashed)])) - return response()->json(['status' => 'success', 'code' => 200, 'message' => 'Password already sent to mail'], 200); - - return response()->json(['status' => 'error', 'code' => 400, 'message' => 'e-mail not found '], 400); + if($request->username) { + $username = $request->username; + $name = $request->username; + } else { + $username = $user->username; + $name = $user->name; + } + $this->reqHttpCurl($email, $hashed, $username, $name); + if(empty($request->password)) { + if (User::where('email', $email)->update(['password' => md5($hashed)])) { + return response()->json(['status' => 'success', 'code' => 200, 'message' => 'Password already sent to mail'], 200); + } + } else { + return response()->json(['status' => 'success', 'code' => 200, 'message' => 'Password already sent to mail'], 200); + } } } @@ -132,7 +147,7 @@ class AuthController extends Controller { $postData = [ "to" => $email, - "username" => $name, + "name" => $name, "username" => $username, "password" => $password, "from" => "app.integrasia@integrasiautama.com", From 90e51a829d83ef7419133785352086a5fab773ce Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 6 Feb 2024 12:53:07 +0700 Subject: [PATCH 084/155] product transaction --- .../ProductTransactionController.php | 30 +++++++++++++++++++ app/Models/ProductTransaction.php | 25 ++++++++++++++++ routes/web.php | 1 + 3 files changed, 56 insertions(+) create mode 100644 app/Http/Controllers/ProductTransactionController.php create mode 100644 app/Models/ProductTransaction.php diff --git a/app/Http/Controllers/ProductTransactionController.php b/app/Http/Controllers/ProductTransactionController.php new file mode 100644 index 0000000..c5d7a12 --- /dev/null +++ b/app/Http/Controllers/ProductTransactionController.php @@ -0,0 +1,30 @@ +validate($request, [ + 'company_id' => 'required|integer', + 'type_paket' => 'required|string', + 'amount' => 'required', + 'exp_ospro' => 'required' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + $result = ProductTransaction::create($data); + + if ($result) { + return response()->json(['status' => 'success','data' => $result, 'message' => 'Add Transaction successfully!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Add data Transaction failed!', 'code' => 400], 400); + } + } +} diff --git a/app/Models/ProductTransaction.php b/app/Models/ProductTransaction.php new file mode 100644 index 0000000..c4a59e5 --- /dev/null +++ b/app/Models/ProductTransaction.php @@ -0,0 +1,25 @@ +group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro // Landing Route $router->post('/send-email', 'AuthController@sendEmail'); $router->post('/company-management-user/add', 'CompanyController@add'); + $router->post('/product-transaction/add','ProductTransactionController@add'); $router->post('/company-management-user/search', 'CompanyController@search'); $router->post('/human-resource-user/add', 'HumanResourceController@add_user'); $router->get('/company-management-user/edit/{id}', 'CompanyController@edit'); From e06111927d7d734daf95f8667b757d43c10e8b79 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 6 Feb 2024 12:53:31 +0700 Subject: [PATCH 085/155] add type_account fillable --- app/Models/Company.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Models/Company.php b/app/Models/Company.php index 403c27d..85e5868 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -33,6 +33,7 @@ class Company extends Model 'updated_at', 'updated_by', 'cluster', + 'type_account', 'date_register' ]; } From b23b22583783ba251649ea0e9f24caedf36775b0 Mon Sep 17 00:00:00 2001 From: wahyun Date: Wed, 7 Feb 2024 16:18:44 +0700 Subject: [PATCH 086/155] implement user & project limit by paket --- .../Controllers/HumanResourceController.php | 28 +++++++++- app/Http/Controllers/ProjectController.php | 51 +++++++++++++++++-- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index 2ea52d7..9b46c9b 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -8,6 +8,7 @@ use App\Models\UserToProyek; use Illuminate\Http\Request; use App\Models\HumanResource; use App\Models\UserToActivity; +use App\Models\ProductTransaction; use Illuminate\Support\Facades\Artisan; const URL_EMAIL = 'https://notifapp.odm-iu.com/service-mail/notif_mail.php'; @@ -30,7 +31,32 @@ class HumanResourceController extends Controller $data['password'] = md5($request->password); } - $result = HumanResource::create($data); + $transaction = ProductTransaction::query() + ->where('company_id', $request->company_id); + $cloneQueryTransaction = clone $transaction; + + $countCreate = false; + $projectResult = HumanResource::query() + ->selectRaw('count(*) as total_hr') + ->where('company_id', $request->company_id) + ->first(); + if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { + if($projectResult['total_hr'] < 10) { + $countCreate = true; + } + } elseif ($cloneQueryTransaction->where([['type_paket','Free'],['amount',0]])->exists()) { + if($projectResult['total_hr'] < 1) { + $countCreate = true; + } + } else { + $countCreate = true; + } + + if($countCreate) { + $result = HumanResource::create($data); + } else { + return response()->json(['status' => 'failed', 'message' => 'Limited to create human resource!', 'code' => 500], 500); + } if ($result) { return response()->json(['status' => 'success', 'message' => 'Human Resource Pool successfull created', 'code' => 200]); diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 0254307..b5ef259 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -38,8 +38,10 @@ use App\Models\ProjectParticipants; use App\Models\FolderDocumentProyek; use App\Models\ProjectToChecklistK3; use App\Helpers\MasterFunctionsHelper; +use App\Models\ProductTransaction; use App\Models\ReportActivityMaterial; use Illuminate\Support\Facades\Artisan; +use Illuminate\Database\Query\Builder; const API_GEOLOCATION = "https://nominatim.oslogdev.com/search/ADDR?format=json&addressdetails=1&limit=1"; @@ -63,10 +65,36 @@ class ProjectController extends Controller $data['created_by'] = $this->currentName; $data['created_by_id'] = $this->currentId; - if (empty($data['phase_id'])) - $data['phase_id'] = 1; - - $result = Project::create($data); + if (empty($data['phase_id'])) { + $data['phase_id'] = 1; + } + + $transaction = ProductTransaction::query() + ->where('company_id', $request->company_id); + $cloneQueryTransaction = clone $transaction; + + $countCreate = false; + $projectResult = Project::query() + ->selectRaw('count(*) as total_project') + ->where('company_id', $request->company_id) + ->first(); + if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { + if($projectResult['total_project'] < 10) { + $countCreate = true; + } + } elseif ($cloneQueryTransaction->where([['type_paket','Free'],['amount',0]])->exists()) { + if($projectResult['total_project'] < 1) { + $countCreate = true; + } + } else { + $countCreate = true; + } + + if($countCreate) { + $result = Project::create($data); + } else { + return response()->json(['status' => 'failed', 'message' => 'Limited to create project!', 'code' => 500], 500); + } if (!$result) return response()->json(['status' => 'failed', 'message' => 'Failed to add data!', 'code' => 500], 500); @@ -531,6 +559,21 @@ class ProjectController extends Controller return response()->json(['status' => 'success', 'message' => 'Set baseline success!', 'code' => 200], 200); } + public function setBaselineActivity($activity_id, $gantt_id) + { + $activity = Activity::where([ + ["version_gantt_id", $gantt_id], + ['id',$activity_id] + ])->first(); + $activity->update([ + "planned_start" => $activity->start_date, + "planned_end" => $activity->end_date, + "early_start" => $activity->start_date, + "early_end" => $activity->end_date, + ]); + return response()->json(['status' => 'success', 'message' => 'Set baseline activity success!', 'code' => 200], 200); + } + public function getInvoiceIntegration(Request $request) { $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); From 1a9800cf30802843c613185137cd6bdb2917b2b3 Mon Sep 17 00:00:00 2001 From: wahyun Date: Wed, 7 Feb 2024 16:19:25 +0700 Subject: [PATCH 087/155] add endpoint baseline per task --- routes/web.php | 1 + 1 file changed, 1 insertion(+) diff --git a/routes/web.php b/routes/web.php index 7acccec..242a752 100644 --- a/routes/web.php +++ b/routes/web.php @@ -76,6 +76,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->delete('/project/delete/{id}', 'ProjectController@delete'); $router->get('/project/list', 'ProjectController@list'); $router->get('/project/set-baseline/{gantt_id}', 'ProjectController@setBaseline'); + $router->get('/project/set-baseline-activity/{activity_id}/{gantt_id}', 'ProjectController@setBaselineActivity'); $router->get('/project/synchronize-report/{gantt_id}', 'ProjectController@synchronizeReport'); $router->get('/project/manpower/{proyek_id}', 'ProjectController@getManpower'); $router->get('/project/manpower/assigned/{gantt_id}', 'ProjectController@getAssignedHR'); From dfe1b86906e216e8c6fa516cee5d391608250266 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 15 Feb 2024 10:17:38 +0700 Subject: [PATCH 088/155] make childern division --- app/Http/Controllers/DivisiController.php | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/app/Http/Controllers/DivisiController.php b/app/Http/Controllers/DivisiController.php index dad48a9..540dd40 100644 --- a/app/Http/Controllers/DivisiController.php +++ b/app/Http/Controllers/DivisiController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Divisi; +use Illuminate\Support\Facades\Log; class DivisiController extends Controller { @@ -83,7 +84,11 @@ class DivisiController extends Controller public function search(Request $request) { - $parentDivisi = Divisi::whereNull('parent')->with('children')->get(); + $companyId = $request->input('columns.0.value'); + $parentDivisi = Divisi::whereNull('parent') + ->where('company_id', $companyId) + ->with('children') + ->get(); $divisions = []; foreach ($parentDivisi as $objRow) { $objRow->children = $this->getAllChildren($objRow); @@ -95,16 +100,6 @@ class DivisiController extends Controller return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); return response()->json(['status' => 'success', 'code' => 200, 'data' => $divisions, 'totalRecord' => $countData], 200); - - // $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); - //return $this->list(); - // cant use builder for this case } public function list() From f88ce60ba87e0a334885b6e8419152e5ee56ffc8 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 15 Feb 2024 10:18:37 +0700 Subject: [PATCH 089/155] update CRUD permission --- app/Http/Controllers/MenuController.php | 118 +++++++++++++----------- app/Models/RoleMenu.php | 2 +- 2 files changed, 66 insertions(+), 54 deletions(-) diff --git a/app/Http/Controllers/MenuController.php b/app/Http/Controllers/MenuController.php index 6ff9324..2aa418e 100644 --- a/app/Http/Controllers/MenuController.php +++ b/app/Http/Controllers/MenuController.php @@ -23,32 +23,33 @@ class MenuController extends Controller $result = Menu::create($data); - if($result){ - return response()->json(['status'=>'success','message'=>'add data menu successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data menu failed!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'message' => 'add data menu successfully!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'add data menu 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); + public function edit($id) + { + if (!$id || (int) $id < 0 || $id == "") { + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); die(); } $result = Menu::find($id); - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data menu, please try again later!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get data menu, 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); + if (!$id || (int) $id < 0 || $id == "") { + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); } $this->validate($request, [ 'icon' => 'required', @@ -58,21 +59,21 @@ class MenuController extends Controller ]); $data = Menu::find($id); - $request->name !== $data['name'] ? $this->validate($request,['name'=>'unique:m_menu,name']) : ''; - $request->url !== $data['url'] ? $this->validate($request,['url'=>'unique:m_menu,url']) : ''; + $request->name !== $data['name'] ? $this->validate($request, ['name' => 'unique:m_menu,name']) : ''; + $request->url !== $data['url'] ? $this->validate($request, ['url' => 'unique:m_menu,url']) : ''; - if($data){ + if ($data) { $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu not found!','code'=>400], 400); + } else { + return response()->json(['status' => 'failed', 'message' => 'data menu not found!', 'code' => 400], 400); die(); } - if($result){ - return response()->json(['status'=>'success','message'=>'data menu successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu failed updated!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'message' => 'data menu successfully updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data menu failed updated!', 'code' => 400], 400); } } @@ -80,18 +81,18 @@ class MenuController extends Controller { $data = Menu::find($id); - if($data){ + if ($data) { $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu not found!','code'=>400], 400); + } else { + return response()->json(['status' => 'failed', 'message' => 'data menu not found!', 'code' => 400], 400); die(); } - if($delete){ - return response()->json(['status'=>'success','message'=>'data menu successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu failed deleted!','code'=>400], 400); + if ($delete) { + return response()->json(['status' => 'success', 'message' => 'data menu successfully deleted!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data menu failed deleted!', 'code' => 400], 400); } } @@ -103,41 +104,52 @@ class MenuController extends Controller $countBuilder = $dataBuilder['count']; $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } public function listMenu($id) { - $dataParent = RoleMenu::select("m_menu.*") - ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') - ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') - ->whereNull('m_menu.parent_id') - ->where('m_roles.id', $id) - ->orderBy('m_menu.sequence', 'ASC') - ->get(); + $dataParent = RoleMenu::select( + 'm_menu.*', + "t_roles_menu.create", + "t_roles_menu.read", + "t_roles_menu.update", + "t_roles_menu.delete" + ) + ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') + ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') + ->whereNull('m_menu.parent_id') + ->where('m_roles.id', $id) + ->orderBy('m_menu.sequence', 'ASC') + ->get(); $finalData = []; - foreach($dataParent as $data){ + foreach ($dataParent as $data) { $data->children = $this->getChildrenMenu($data->id, $id); $finalData[] = $data; } - return response()->json(['status'=>'success','code'=>200,'data'=>$finalData], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $finalData], 200); } protected function getChildrenMenu($id, $role_id) { - $dataChildren = RoleMenu::select("m_menu.*") - ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') - ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') - ->where('m_roles.id', $role_id) - ->where('m_menu.parent_id', $id) - ->orderBy('m_menu.sequence', 'ASC') - ->get(); + $dataChildren = RoleMenu::select( + 'm_menu.*', + "t_roles_menu.create", + "t_roles_menu.read", + "t_roles_menu.update", + "t_roles_menu.delete" + ) + ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') + ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') + ->where('m_roles.id', $role_id) + ->where('m_menu.parent_id', $id) + ->orderBy('m_menu.sequence', 'ASC') + ->get(); $children = []; - if($dataChildren){ - foreach($dataChildren as $data) - { + if ($dataChildren) { + foreach ($dataChildren as $data) { $data->children = $this->getChildrenMenu($data->id, $role_id); $children[] = $data; } @@ -150,10 +162,10 @@ class MenuController extends Controller $data = Menu::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 menu, please try again later!','code'=>400], 400); + if ($data) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data, 'totalRecord' => $countData], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get list menu, please try again later!', 'code' => 400], 400); } } } diff --git a/app/Models/RoleMenu.php b/app/Models/RoleMenu.php index 3540ea6..70fa437 100644 --- a/app/Models/RoleMenu.php +++ b/app/Models/RoleMenu.php @@ -12,6 +12,6 @@ class RoleMenu extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'role_id', 'menu_id', 'created_at', 'created_by', 'updated_at', 'updated_by' + 'role_id', 'menu_id', 'create', 'read', 'update', 'delete', 'created_at', 'created_by', 'updated_at', 'updated_by' ]; } From 519136114fbe3dcccc5947a937845dbd3efc5da0 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 15 Feb 2024 10:23:46 +0700 Subject: [PATCH 090/155] report analysis user group update --- .../Controllers/UserToActivityController.php | 227 ++++++++++-------- 1 file changed, 125 insertions(+), 102 deletions(-) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index bfe4f22..b6f9926 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -11,7 +11,8 @@ use Datatables; class UserToActivityController extends Controller { - public function add(Request $request){ + public function add(Request $request) + { $this->validate($request, [ 'activity_id' => 'required', 'user_id' => 'required' @@ -20,24 +21,25 @@ class UserToActivityController extends Controller $data = $request->all(); $data['created_by'] = $this->currentName; - if(!UserToActivity::create($data)) - return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500]); + 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]); + return response()->json(['status' => 'success', 'message' => 'Data added!', 'code' => 200]); } - public function addMultiple(Request $request){ + public function addMultiple(Request $request) + { $users_id = $request->user_id; - $users_role = $request->role_proyek_id; + $users_role = $request->role_proyek_id; // $data = UserToActivity::where("activity_id", $request->activity_id); // if($data){ // $data->delete(); // } - if(is_array($users_id) && count($users_id) > 0){ + if (is_array($users_id) && count($users_id) > 0) { $countRes = 0; - foreach($users_id as $index => $item){ + foreach ($users_id as $index => $item) { $dataInsert = array( "user_id" => $item, "activity_id" => $request->activity_id, @@ -45,89 +47,91 @@ class UserToActivityController extends Controller "proyek_id" => $request->proyek_id, "start_date" => $request->start_date, "end_date" => $request->end_date, - "created_by" => $this->currentName, - "version_gantt_id" => $request->version_gantt_id + "created_by" => $this->currentName, + "version_gantt_id" => $request->version_gantt_id ); $result = UserToActivity::create($dataInsert); - if($result){ + if ($result) { $countRes++; - }else{ + } else { $countRes--; } } - if($countRes == 0) - return response()->json(['status'=>'failed' ,'message'=>'Failed to add data!','code'=> 500]); + 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 + "rencana_biaya" => $allCost, + "updated_by" => $this->currentName ); $actUpdate = Activity::find($request->activity_id); - if($actUpdate){ + if ($actUpdate) { $actUpdate->update($dataUpdateCost); - if($actUpdate->parent_id){ + 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]); + return response()->json(['status' => 'success', 'message' => 'Data added!', 'code' => 200]); + } else { + return response()->json(['status' => 'success', 'message' => 'Data added!', 'code' => 200]); } - } - private function updatedCostPlanning($parent_id) { + private function updatedCostPlanning($parent_id) + { $sumBiaya = Activity::selectRaw('sum(cast(rencana_biaya as double precision))') ->where("parent_id", $parent_id) ->first(); - if($parent = Activity::find($parent_id)){ + if ($parent = Activity::find($parent_id)) { $parent->update([ "rencana_biaya" => $sumBiaya->sum, ]); } - } + } - 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); + 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) + 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); + 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); + 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) + 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); + 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); + 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); + 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); + 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); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); } public function searchAnalysis(Request $request) @@ -135,14 +139,21 @@ class UserToActivityController extends Controller $dataBuilder = $this->setUpPayload($request->all(), 'assign_hr_to_activity'); $builder = $dataBuilder['builder']; $countBuilder = $dataBuilder['count']; - $builder->addSelect(DB::raw('SUM(report_activity_material.qty) as volume_actual')); - $builder->groupBy("m_activity.id"); - $builder->groupBy("selfTable.id"); - $builder->groupBy("selfTable.start_date"); - $builder->groupBy("selfTable.end_date"); - $builder->groupBy("m_users.name"); - $builder->groupBy("assign_material_to_activity.id"); - $builder->groupBy("m_version_gantt.name_version"); + $builder->addSelect(DB::raw('SUM(report_activity_material.qty) as volume_actual')); + $builder->groupBy("m_activity.name"); + $builder->groupBy("m_activity.persentase_progress"); + $builder->groupBy("m_activity.actual_start"); + $builder->groupBy("m_activity.actual_end"); + $builder->groupBy("m_activity.planned_start"); + $builder->groupBy("m_activity.planned_end"); + $builder->groupBy("m_activity.start_date"); + $builder->groupBy("m_activity.end_date"); + $builder->groupBy("m_activity.duration"); + $builder->groupBy("selfTable.id"); + $builder->groupBy("selfTable.start_date"); + $builder->groupBy("selfTable.end_date"); + $builder->groupBy("assign_material_to_activity.qty_planning"); + $builder->groupBy("m_version_gantt.name_version"); $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); @@ -165,7 +176,7 @@ class UserToActivityController extends Controller $status = $join_column['status']; $startDate = date("Y-m-d H:i:sO", strtotime($startDate)); $endDate = date("Y-m-d H:i:sO", strtotime($endDate)); - $builder->where(function ($query) use ($startDate, $endDate) { + $builder->where(function ($query) use ($startDate, $endDate) { $query ->where('m_proyek.mulai_proyek', '>=', $startDate) ->where('m_proyek.akhir_proyek', '<=', $endDate) @@ -188,22 +199,33 @@ class UserToActivityController extends Controller $dataGet = $filteredData; } // $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>count($dataGet)], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => count($dataGet)], 200); } - public function activityUser(Request $request){ + public function activityUser(Request $request) + { $payload = $request->all(); $activity = DB::table('m_activity as ma') - ->select('ahta.id', 'ma.id as activity_id', 'ma.proyek_id', 'ma.name as join_second_name', 'ma.start_date as join_second_start_date', - 'ma.end_date as join_second_end_date', 'ma.persentase_progress', 'mvg.name_version', 'mp.nama as nama_proyek', 'mp.type_proyek_id') - ->join('assign_hr_to_activity as ahta', 'ahta.activity_id', '=', 'ma.id') - ->join('m_version_gantt as mvg', 'mvg.id', '=', 'ma.version_gantt_id') - ->join('m_proyek as mp', 'mp.id', '=', 'ma.proyek_id') - ->where('ahta.user_id', $payload['user_id']) - ->where('ma.start_date', '<=', $payload['end_date']) - ->where('ma.end_date', '>=', $payload['start_date']) - ->where('ma.proyek_id', $payload['proyek_id']) - ->get(); + ->select( + 'ahta.id', + 'ma.id as activity_id', + 'ma.proyek_id', + 'ma.name as join_second_name', + 'ma.start_date as join_second_start_date', + 'ma.end_date as join_second_end_date', + 'ma.persentase_progress', + 'mvg.name_version', + 'mp.nama as nama_proyek', + 'mp.type_proyek_id' + ) + ->join('assign_hr_to_activity as ahta', 'ahta.activity_id', '=', 'ma.id') + ->join('m_version_gantt as mvg', 'mvg.id', '=', 'ma.version_gantt_id') + ->join('m_proyek as mp', 'mp.id', '=', 'ma.proyek_id') + ->where('ahta.user_id', $payload['user_id']) + ->where('ma.start_date', '<=', $payload['end_date']) + ->where('ma.end_date', '>=', $payload['start_date']) + ->where('ma.proyek_id', $payload['proyek_id']) + ->get(); if ($payload['status'] != "") { $filteredData = []; @@ -215,7 +237,7 @@ class UserToActivityController extends Controller } $activity = $filteredData; } - return response()->json(['status'=>'success','code'=>200,'data'=>$activity, 'totalRecord'=>count($activity)], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $activity, 'totalRecord' => count($activity)], 200); } public function list() @@ -223,46 +245,47 @@ class UserToActivityController extends Controller $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); + 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 listFiltered(Request $request) + public function listFiltered(Request $request) { - $startDate = $request->start_date; - $endDate = $request->end_date; - $userId = $request->user_id; - $proyekId = $request->proyek_id; - - if (isset($proyekId)) { - $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') - ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') - ->where('m_activity.start_date', '=', $startDate) - ->where('m_activity.end_date', '=', $endDate) - ->where('assign_hr_to_activity.user_id', '=', $userId) - ->where('assign_hr_to_activity.proyek_id', '=', $proyekId) - ->get(); - }else { - $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') - ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') - ->where('m_activity.start_date', '=', $startDate) - ->where('m_activity.end_date', '=', $endDate) - ->where('assign_hr_to_activity.user_id', '=', $userId) - ->get(); - } - $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); + $startDate = $request->start_date; + $endDate = $request->end_date; + $userId = $request->user_id; + $proyekId = $request->proyek_id; + + if (isset($proyekId)) { + $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') + ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') + ->where('m_activity.start_date', '=', $startDate) + ->where('m_activity.end_date', '=', $endDate) + ->where('assign_hr_to_activity.user_id', '=', $userId) + ->where('assign_hr_to_activity.proyek_id', '=', $proyekId) + ->get(); + } else { + $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') + ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') + ->where('m_activity.start_date', '=', $startDate) + ->where('m_activity.end_date', '=', $endDate) + ->where('assign_hr_to_activity.user_id', '=', $userId) + ->get(); + } + $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){ + public function datatables(Request $request) + { $id_activity = $request->query('idact'); $data = UserToActivity::select("assign_hr_to_activity.id as id", "assign_hr_to_activity.start_date", "assign_hr_to_activity.end_date", "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") @@ -271,8 +294,8 @@ class UserToActivityController extends Controller ->get(); return Datatables::of($data) ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; + ->addColumn('action', function ($row) { + $actionBtn = ''; return $actionBtn; }) ->rawColumns(['action'])->make(true); From 0cc9e67a7efecd600ee9fa29203a9dbb1633163f Mon Sep 17 00:00:00 2001 From: wahyun Date: Mon, 19 Feb 2024 17:04:15 +0700 Subject: [PATCH 091/155] add limits storage --- app/Http/Controllers/ActivityController.php | 40 ++-- .../Controllers/ActivityDokumenController.php | 71 +++--- app/Http/Controllers/Controller.php | 122 +++++++++- app/Http/Controllers/ImageController.php | 78 +++++-- app/Http/Controllers/ProjectController.php | 75 +++--- .../Controllers/ProjectDokumenController.php | 219 +++++++++--------- .../Controllers/UserToProyekController.php | 31 +-- routes/web.php | 30 ++- 8 files changed, 432 insertions(+), 234 deletions(-) diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index 44f5a2a..55e0444 100755 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -5,6 +5,7 @@ namespace App\Http\Controllers; use DateTime; use App\Models\Link; use App\Models\User; +use App\Models\Company; use App\Models\Project; use App\Models\Activity; use App\Models\TmpImport; @@ -16,6 +17,7 @@ use App\Models\AssignMaterial; use App\Models\UserToActivity; use App\Models\ActivityDokumen; use App\Models\CommentActivity; +use App\Models\ProductTransaction; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use App\Helpers\MasterFunctionsHelper; @@ -626,28 +628,32 @@ class ActivityController extends Controller return response()->json(['status' => 'success', 'message' => 'Activity Updated!', 'code' => 200], 200); } - public function delete($id) + public function delete($id, $company_id) { if (!$data = Activity::find($id)) return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 404], 404); - $this->deleteRelative($id); + $this->deleteRelative($id, $company_id); if (!$data->delete()) return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'data activity failed deleted!', 'code' => 500], 500); return response()->json(['status' => 'success', "action" => "deleted", 'message' => 'data activity successfully deleted!', 'code' => 200], 200); } - private function deleteRelative($activity_id) + private function deleteRelative($activity_id, $company_id) { UserToActivity::where('activity_id', $activity_id)->delete(); AssignMaterial::where('activity_id', $activity_id)->delete(); $dataAd = ActivityDokumen::where("activity_id", $activity_id)->get(); - foreach ($dataAd as $ad) { - if (file_exists($this->pathActivityDocument . $ad->file)) { - unlink($this->pathActivityDocument . $ad->file); - } - } - ActivityDokumen::where("activity_id", $activity_id)->delete(); + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + foreach ($dataAd as $ad) { + if (file_exists($destinationPath['pathActivityDocument'] . $ad->file)) { + unlink($destinationPath['pathActivityDocument'] . $ad->file); + } + } + ActivityDokumen::where("activity_id", $activity_id)->delete(); + } } public function getUpdate($id) @@ -1124,18 +1130,22 @@ class ActivityController extends Controller $document = $request->file('dokumen'); $gantt_id = $request->gantt_id; $name = $document->getClientOriginalName(); - - $result = $document->move($this->pathTmpImport, $name); - if ($result) { + // Limited Storage + $company = Company::where('company_name', $request->company_name)->first(); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $getLimitStorage = $this->setLimitsStorage($company, $document, $name, $destinationPath['pathTmpImport'], $destinationPath); + } + if (isset($getLimitStorage) && $getLimitStorage['resultMove']) { $data = [ 'gantt_id' => (int) $gantt_id, 'file' => $name, 'type_dokumen' => $request->type_dokumen ]; - $result = TmpImport::create($data); + $getLimitStorage['resultMove'] = TmpImport::create($data); - if (!$result) { + if (!$getLimitStorage['resultMove']) { unlink($this->pathTmpImport . $name); return response()->json(['status' => 'failed', 'message' => 'Upload failed!', 'code' => 500], 500); } @@ -1161,6 +1171,6 @@ class ActivityController extends Controller // public function recalculateProject($by, $id){ // // query get activity - // $cekActivity = + // $cekActivity = // } } diff --git a/app/Http/Controllers/ActivityDokumenController.php b/app/Http/Controllers/ActivityDokumenController.php index 999e860..0cfd83b 100644 --- a/app/Http/Controllers/ActivityDokumenController.php +++ b/app/Http/Controllers/ActivityDokumenController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Models\Company; use Illuminate\Http\Request; use App\Models\ActivityDokumen; @@ -16,50 +17,52 @@ class ActivityDokumenController extends Controller return response()->json(['status'=>'success','data'=>$dataDokumen,'code'=>200], 200); } - public function delete($id) + public function delete($id, $company_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); - + if(!$document) { + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + } + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + if(file_exists($destinationPath['pathActivityDocument'].$document->file)){ + unlink($destinationPath['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); - + 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) + $company = Company::find($request->company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $result = $document->move($destinationPath['pathActivityDocument'], $name); + } + if(!$result || !$company) 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); + if(!$result || !$company){ + unlink($destinationPath['pathActivityDocument'].$name); return response()->json(['status'=>'failed','message'=>'Upload failed!','code'=> 500], 500); } - return response()->json(['status'=>'success','message'=>'Upload success!','code'=>200], 200); } @@ -75,21 +78,23 @@ class ActivityDokumenController extends Controller return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); } - public function downloadDokumen($id) + public function downloadDokumen($id, $company_id) { - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); - + 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); - } - + $company = Company::find($company_id); + if(!$document || !$company) { + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>400], 400); + } + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + if(file_exists($destinationPath['pathActivityDocument'].$document->file)) { + $pathToFile = $destinationPath['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/Controller.php b/app/Http/Controllers/Controller.php index a084601..33046be 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -2,16 +2,17 @@ namespace App\Http\Controllers; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Http; -use App\Models\UserToActivity; +use App\Models\User; +use App\Models\Divisi; use App\Models\Activity; use App\Models\AssignMaterial; -use App\Models\Divisi; -use App\Models\User; -use Laravel\Lumen\Routing\Controller as BaseController; - use App\Models\ReportK3Detail; +use App\Models\UserToActivity; +use App\Models\ProductTransaction; +use Illuminate\Support\Facades\DB; + +use Illuminate\Support\Facades\Http; +use Laravel\Lumen\Routing\Controller as BaseController; class Controller extends BaseController { @@ -38,6 +39,91 @@ class Controller extends BaseController $this->pathActivityDocument = config('assets.activity'); } + protected function setCustomeDirectoryUpload($company_name) + { + $pathImage = 'assets/'.$company_name.'/image/'; + $pathDocument = 'assets/'.$company_name.'/file/project/'; + $pathTmpImport = 'assets/'.$company_name.'/file/tmpimport/'; + $pathActivityDocument = 'assets/'.$company_name.'/file/activity/'; + + return [ + 'pathImage' => $pathImage, + 'pathDocument' => $pathDocument, + 'pathTmpImport' => $pathTmpImport, + 'pathActivityDocument' => $pathActivityDocument + ]; + } + + protected function setLimitsStorage($company, $dokumen, $name, $initPath, $destinatePath) { + $totalSize = 0; + $sizeFile = $dokumen->getSize(); + // Path + $folderPath = $destinatePath['pathDocument']; + $folderPathImage = $destinatePath['pathImage']; + $folderPathTmpImport = $destinatePath['pathTmpImport']; + $folderPathActivityDocument = $destinatePath['pathActivityDocument']; + // Create Directory + if(!file_exists($initPath)) { + mkdir($initPath, 0777, true); + } + // Scanning & Existing Folder + if(file_exists($folderPathImage)) { + $files = scandir($folderPathImage); + foreach ($files as $file) { + if (is_file($folderPathImage . '/' . $file)) { + $totalSize += filesize($folderPathImage . '/' . $file); + } + } + } + if(file_exists($folderPath)) { + $filesImage = scandir($folderPath); + foreach ($filesImage as $file) { + if (is_file($folderPath . '/' . $file)) { + $totalSize += filesize($folderPath . '/' . $file); + } + } + } + if(file_exists($folderPathTmpImport)) { + $filesTmpImport = scandir($folderPathTmpImport); + foreach ($filesTmpImport as $file) { + if (is_file($folderPathTmpImport . '/' . $file)) { + $totalSize += filesize($folderPathTmpImport . '/' . $file); + } + } + } + if(file_exists($folderPathActivityDocument)) { + $filesActivityDocument = scandir($folderPathActivityDocument); + foreach ($filesActivityDocument as $file) { + if (is_file($folderPathActivityDocument . '/' . $file)) { + $totalSize += filesize($folderPathActivityDocument . '/' . $file); + } + } + } + // Logic + $totalSize += $sizeFile; + $transaction = ProductTransaction::query() + ->where('company_id', $company['id']); + $cloneQueryTransaction = clone $transaction; + $countCreate = false; + if($transaction->where([['type_paket','Basic'], ['amount','!=',null]])->exists()) { + $maximumSize = 500 * 1024 * 1024; + $countCreate = true; + } elseif ($cloneQueryTransaction->where([['type_paket','Free'], ['amount', 0]])->exists()) { + $maximumSize = 50 * 1024 * 1024; + $countCreate = true; + } + if($countCreate) { + if ($totalSize > $maximumSize) { + return response()->json(['status'=>'failed','message'=>'Limited storage maximum!','code'=> 500], 500); + } + } + $resultMove = $dokumen->move($folderPath, $name); + + return [ + 'resultMove' => $resultMove + ]; + } + protected function setUpPayload($condition, $tableSelf) { $alias = "selfTable"; @@ -280,6 +366,28 @@ class Controller extends BaseController return $totalCost; } + protected function paramsMethodGet($query, $countData, $request) + { + $start = $request->start; + $length = $request->length == '-1' ? $countData : $request->length; + $orderBy = $request->orderby; + $asc = $request->asc == 'false' ? 'desc' : 'asc'; + $where = $request->column; + $logicOp = $request->logic; + $valColumn = str_replace("\\", "", "$request->value"); + + if ($logicOp == 'like' || $logicOp == 'ilike') { + $valColumnFilter = '%' . $valColumn . '%'; + } else { + $valColumnFilter = $valColumn; + } + $data = $query->where($where, $logicOp, $valColumnFilter) + ->orderBy($orderBy, $asc) + ->offset($start)->limit($length)->get(); + + return $data; + } + protected function getLoc($lat, $lng) { // $response = Http::get(config('api.nominatim') . "/reverse?lat=".$lat."&lon=".$lng."&format=json"); diff --git a/app/Http/Controllers/ImageController.php b/app/Http/Controllers/ImageController.php index a7b9de5..aa8adbe 100644 --- a/app/Http/Controllers/ImageController.php +++ b/app/Http/Controllers/ImageController.php @@ -2,9 +2,10 @@ namespace App\Http\Controllers; +use App\Models\Image; use App\Models\Company; use Illuminate\Http\Request; -use App\Models\Image; +use App\Models\ProductTransaction; class ImageController extends Controller { @@ -22,10 +23,13 @@ class ImageController extends Controller $extension = $dokumen->extension(); $category = $request->category; $name = $ref_id.date("YmdHis").".".$extension; - - $resultMove = $dokumen->move($this->pathImage, $name); - - if($resultMove){ + // Limited Storage + $company = Company::where('company_name', $request->company_name)->first(); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $getLimitStorage = $this->setLimitsStorage($company, $dokumen, $name, $destinationPath['pathImage'], $destinationPath); + } + if(isset($getLimitStorage) && $getLimitStorage['resultMove']) { $data = [ 'ref_id' => (int)$ref_id, 'image' => $name, @@ -63,7 +67,7 @@ class ImageController extends Controller if($result){ return response()->json(['status'=>'success', "name_image"=>$name,'message'=>'image upload is successfully!','code'=>200], 200); }else{ - unlink($this->pathImage.$name); + unlink($destinationPath['pathImage'].$name); return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); } @@ -88,11 +92,50 @@ class ImageController extends Controller $dokumen = $request->file('files'); $successCount = 0; $imageSlider = []; + // Limited Storage + $company = Company::where('company_name', $request->company_name)->first(); + if($company) { + $totalSize = 0; + $sizeFile = $dokumen->getSize(); + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $folderPath = $destinationPath['pathImage']; + + if (!file_exists($folderPath)) { + mkdir($folderPath, 0777, true); + } + + $files = scandir($folderPath); + $totalSize = 0; + + foreach ($files as $file) { + if (is_file($folderPath . '/' . $file)) { + $totalSize += filesize($folderPath . '/' . $file); + } + } + $totalSize += $sizeFile; + $transaction = ProductTransaction::query() + ->where('company_id', $company['id']); + $cloneQueryTransaction = clone $transaction; + + $countCreate = false; + if($transaction->where([['type_paket','Basic'], ['amount','!=',null]])->exists()) { + $maximumSize = 500 * 1024 * 1024; + $countCreate = true; + } elseif ($cloneQueryTransaction->where([['type_paket','Free'], ['amount', 0]])->exists()) { + $maximumSize = 50 * 1024 * 1024; + $countCreate = true; + } + if($countCreate) { + if ($totalSize > $maximumSize) { + return response()->json(['status'=>'failed','message'=>'Limited storage maximum!','code'=> 500], 500); + } + } + } foreach ($dokumen as $file) { $extension = $file->extension(); $name = $ref_id.date("YmdHis").$successCount.".".$extension; - $resultMove = $file->move($this->pathImage, $name); + $resultMove = $file->move($folderPath, $name); if ($resultMove) { $data = [ @@ -107,7 +150,7 @@ class ImageController extends Controller if ($result) { $successCount++; } else { - unlink($this->pathImage . $name); + unlink($folderPath . $name); } } } @@ -147,8 +190,6 @@ class ImageController extends Controller return response()->json(['status'=>'failed','message'=>'data image not found!','code'=>400], 400); die(); } - - if($delete){ return response()->json(['status'=>'success','message'=>'data image successfully deleted!','code'=>200], 200); }else{ @@ -167,12 +208,13 @@ class ImageController extends Controller return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); } - public function deleteByRef($id, $category) + public function deleteByRef($id, $category, $company_id) { $data = Image::where("ref_id", intval($id))->where("category", $category)->first(); - - if($data){ - unlink($this->pathImage.$data->image); + $company = Company::find($company_id); + if($data && $company){ + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + unlink($destinationPath['pathImage'].$data->image); $delete = $data->delete(); }else{ return response()->json(['status'=>'failed','message'=>'data image not found!','code'=>400], 400); @@ -187,16 +229,18 @@ class ImageController extends Controller } } - public function deleteByRefMultiple($id, $category) + public function deleteByRefMultiple($id, $category, $company_id) { $successCount = 0; $data = Image::where([ ["ref_id", intval($id)], ["category", $category] ])->get(); - if($data->isNotEmpty()) { + $company = Company::find($company_id); + if($data->isNotEmpty() && $company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); foreach($data as $img) { - unlink($this->pathImage.$img->image); + unlink($destinationPath['pathImage'].$img->image); $delete = $img->delete(); if($delete){ $successCount++; diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index b5ef259..0f4e54b 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -6,6 +6,7 @@ use DateTime; use App\Models\Link; use App\Models\User; use App\Models\Image; +use App\Models\Company; use App\Models\Holiday; use App\Models\Project; use App\Models\Activity; @@ -33,15 +34,15 @@ use App\Models\ProjectApproval; use App\Models\RequestMaterial; use App\Models\ProjectMileStone; use App\Models\ProjectChecklists; +use App\Models\ProductTransaction; use Illuminate\Support\Facades\DB; use App\Models\ProjectParticipants; use App\Models\FolderDocumentProyek; use App\Models\ProjectToChecklistK3; use App\Helpers\MasterFunctionsHelper; -use App\Models\ProductTransaction; use App\Models\ReportActivityMaterial; -use Illuminate\Support\Facades\Artisan; use Illuminate\Database\Query\Builder; +use Illuminate\Support\Facades\Artisan; const API_GEOLOCATION = "https://nominatim.oslogdev.com/search/ADDR?format=json&addressdetails=1&limit=1"; @@ -206,14 +207,14 @@ class ProjectController extends Controller return true; } - public function delete($id) + public function delete($id, $company_id) { $data = Project::find($id); if (!$data) return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - $this->deleteRelative($id); + $this->deleteRelative($id, $company_id); if (!$data->delete()) return response()->json(['status' => 'failed', 'message' => 'Delete failed!', 'code' => 500], 500); @@ -221,7 +222,7 @@ class ProjectController extends Controller return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); } - private function deleteRelative($project_id) + private function deleteRelative($project_id, $company_id) { UserToProyek::where('proyek_id', $project_id)->delete(); UserToActivity::where('proyek_id', $project_id)->delete(); @@ -239,32 +240,36 @@ class ProjectController extends Controller OfficeHours::where('proyek_id', $project_id)->delete(); ReportK3::where('proyek_id', $project_id)->delete(); RequestMaterial::where('proyek_id', $project_id)->delete(); - $this->deleteVersionGantt($project_id); - $this->deleteDokumenProject($project_id); + $this->deleteVersionGantt($project_id, $company_id); + $this->deleteDokumenProject($project_id, $company_id); } - private function deleteVersionGantt($project_id) + private function deleteVersionGantt($project_id, $company_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); - } - } + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + foreach ($dataRa as $ra) { + $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); + foreach ($images as $image) { + if (file_exists($destinationPath['pathImage'] . $image->image)) { + unlink($destinationPath['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($destinationPath['pathActivityDocument'] . $ad->file)) { + unlink($destinationPath['pathActivityDocument'] . $ad->file); + } + } + } ActivityDokumen::whereIn("activity_id", $activityIds)->delete(); CommentActivity::whereIn("activity_id", $activityIds)->delete(); Holiday::where("proyek_id", $project_id)->delete(); @@ -275,23 +280,26 @@ class ProjectController extends Controller ReportActivity::whereIn("activity_id", $activityIds)->delete(); } - private function deleteDokumenProject($project_id) + private function deleteDokumenProject($project_id, $company_id) { $dataDokumen = DokumenProject::where("type_dokumen", "project-document-out-folder")->where('ref_id', $project_id)->get(); + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + foreach ($dataDokumen as $dokumen) { + if (file_exists($destinationPath['pathDocument'] . $dokumen->file)) { + unlink($destinationPath['pathDocument'] . $dokumen->file); + } + } + } - 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); + if (file_exists($destinationPath['pathDocument'] . $dokumen->file)) { + unlink($destinationPath['pathDocument'] . $dokumen->file); } } @@ -520,9 +528,6 @@ class ProjectController extends Controller } $activity->save(); } - /* return response()->json(['status'=>'success','data'=> $reports,'code'=>200], 200); */ - /* return response()->json(['status'=>'success','data'=> $activities,'code'=>200], 200); */ - for ($i = 0; $i < count($reports); $i++) { $activity = Activity::find($reports[$i]['activity_id']); if ($reports[$i]['status'] != 'done') { diff --git a/app/Http/Controllers/ProjectDokumenController.php b/app/Http/Controllers/ProjectDokumenController.php index 963208c..d9e4f04 100644 --- a/app/Http/Controllers/ProjectDokumenController.php +++ b/app/Http/Controllers/ProjectDokumenController.php @@ -1,105 +1,114 @@ -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; - $name = pathinfo($pathToFile, PATHINFO_FILENAME) . "." . pathinfo($pathToFile, PATHINFO_EXTENSION); - $headers = [ - 'Content-Disposition' => 'attachment; filename="'.$name.'"' - ]; - // dd($name, $headers); - return response()->download($pathToFile, $name, $headers); - } -} +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, $company_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); + } + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + if(file_exists($destinationPath['pathDocument'].$document->file)){ + unlink($destinationPath['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(); + // Limited Storage + $company = Company::where('company_name', $request->company_name)->first(); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $getLimitStorage = $this->setLimitsStorage($company, $document, $name, $destinationPath['pathDocument'],$destinationPath); + } + if(isset($getLimitStorage) && $getLimitStorage['resultMove']) { + $data = [ + 'ref_id' => (int)$ref_id, + 'file' => $name, + 'type_dokumen' => isset($request->type_dokumen) ? $request->type_dokumen : 'project-document' + ]; + + $getLimitStorage['resultMove'] = DokumenProject::create($data); + + if(!$getLimitStorage['resultMove']){ + unlink($destinationPath['pathDocument'].$name); + return response()->json(['status'=>'failed','message'=>'Dokumen project gagal diupload!','code'=> 500], 500); + } + return response()->json(['status'=>'success','message'=>'Dokumen project berhasil diupload!','code'=>200], 200); + } + return response()->json(['status'=>'failed','message'=>'Dokumen project gagal diupload!','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, $company_id) + { + if(empty($id) || !is_int((int)$id)) { + return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); + } + $document = DokumenProject::find($id); + $company = Company::find($company_id); + if(!$document || !$company) { + 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); + } + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $pathToFile = $destinationPath['pathDocument'].$document->file; + $name = pathinfo($pathToFile, PATHINFO_FILENAME) . "." . pathinfo($pathToFile, PATHINFO_EXTENSION); + } + $headers = [ + 'Content-Disposition' => 'attachment; filename="'.$name.'"' + ]; + + return response()->download($pathToFile, $name, $headers); + } +} diff --git a/app/Http/Controllers/UserToProyekController.php b/app/Http/Controllers/UserToProyekController.php index 1f6e55c..7bfab8f 100644 --- a/app/Http/Controllers/UserToProyekController.php +++ b/app/Http/Controllers/UserToProyekController.php @@ -2,11 +2,12 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; +use App\Models\Image; +use App\Models\Company; use App\Models\UserToProyek; -use App\Models\UserToActivity; +use Illuminate\Http\Request; use App\Models\ReportActivity; -use App\Models\Image; +use App\Models\UserToActivity; class UserToProyekController extends Controller { @@ -111,7 +112,7 @@ class UserToProyekController extends Controller } } - public function delete($id) + public function delete($id, $company_id) { $data = UserToProyek::find($id); if($data){ @@ -119,7 +120,7 @@ class UserToProyekController extends Controller $proyekId = $data->proyek_id; $delete = $data->delete(); if($delete){ - $this->deleteRelative($proyekId, $userId); + $this->deleteRelative($proyekId, $userId, $company_id); } }else{ return response()->json(['status'=>'failed','message'=>'data assign hr to proyek not found!','code'=>400], 400); @@ -134,21 +135,25 @@ class UserToProyekController extends Controller } } - private function deleteRelative($proyekId, $userId) + private function deleteRelative($proyekId, $userId, $company_id) { $uta = UserToActivity::where("proyek_id", $proyekId)->where("user_id", $userId)->get(); foreach ($uta as $value) { $dataRa = ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->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); + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + foreach ($dataRa as $ra) { + $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); + foreach ($images as $image) { + if(file_exists($destinationPath['pathImage'].$image->image)){ + unlink($destinationPath['pathImage'].$image->image); + } } + Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); } - Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); + ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->delete(); } - ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->delete(); } UserToActivity::where("proyek_id", $proyekId)->where("user_id", $userId)->delete(); } diff --git a/routes/web.php b/routes/web.php index 242a752..19a4bd4 100644 --- a/routes/web.php +++ b/routes/web.php @@ -57,15 +57,15 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/document-project/upload', 'ProjectDokumenController@uploadProjectDokumen'); $router->get('/document-project/get/{id}', 'ProjectDokumenController@dokumenByProyekId'); - $router->delete('/document-project/delete/{id}', 'ProjectDokumenController@delete'); + $router->delete('/document-project/delete/{id}/{company_id}', 'ProjectDokumenController@delete'); $router->post('/document-project/search', 'ProjectDokumenController@searchDocProject'); - $router->get('/document-project/download/{id}', 'ProjectDokumenController@downloadDokumen'); + $router->get('/document-project/download/{id}/{company_id}', 'ProjectDokumenController@downloadDokumen'); $router->post('/document-activity/upload', 'ActivityDokumenController@uploadProjectDokumen'); $router->get('/document-activity/get/{id}', 'ActivityDokumenController@dokumenByActivityId'); - $router->delete('/document-activity/delete/{id}', 'ActivityDokumenController@delete'); + $router->delete('/document-activity/delete/{id}/{company_id}', 'ActivityDokumenController@delete'); $router->post('/document-activity/search', 'ActivityDokumenController@searchDocProject'); - $router->get('/document-activity/download/{id}', 'ActivityDokumenController@downloadDokumen'); + $router->get('/document-activity/download/{id}/{company_id}', 'ActivityDokumenController@downloadDokumen'); $router->get('/project-by-customer/{id}', 'ProjectController@getByUser'); $router->post('/project/search', 'ProjectController@search'); @@ -73,7 +73,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->put('/project/update/{id}', 'ProjectController@update'); $router->get('/project/edit/{id}', 'ProjectController@edit'); $router->get('/project/detail/{id}[/{gantt_id}[/{s_curve}]]', 'ProjectController@detail'); - $router->delete('/project/delete/{id}', 'ProjectController@delete'); + $router->delete('/project/delete/{id}/{company_id}', 'ProjectController@delete'); $router->get('/project/list', 'ProjectController@list'); $router->get('/project/set-baseline/{gantt_id}', 'ProjectController@setBaseline'); $router->get('/project/set-baseline-activity/{activity_id}/{gantt_id}', 'ProjectController@setBaselineActivity'); @@ -263,7 +263,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/task/edit/{id}', 'ActivityController@edit'); $router->put('/task/{id}', 'ActivityController@update'); $router->put('/task/update-regular/{id}', 'ActivityController@updateRegular'); - $router->delete('/task/{id}', 'ActivityController@delete'); + $router->delete('/task/{id}/{company_id}', 'ActivityController@delete'); $router->get('/task/get-update/{id}', 'ActivityController@getUpdate'); $router->post('/tmp-import/upload', 'ActivityController@uploadTmpImport'); @@ -324,8 +324,8 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/image/search', 'ImageController@search'); $router->delete('/image/delete/{id}', 'ImageController@delete'); - $router->delete('/image/delete/{id}/{category}', 'ImageController@deleteByRef'); - $router->delete('/image/multiple-delete/{id}/{category}', 'ImageController@deleteByRefMultiple'); + $router->delete('/image/delete/{id}/{category}/{company_id}', 'ImageController@deleteByRef'); + $router->delete('/image/multiple-delete/{id}/{category}/{company_id}', 'ImageController@deleteByRefMultiple'); $router->post('/image/upload', 'ImageController@uploadImage'); $router->post('/image/multiple-upload', 'ImageController@uploadMultipleImage'); $router->get('/image/{id}/{category}', 'ImageController@getByRefId'); @@ -362,6 +362,18 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/project-issues/list', 'ProjectIssuesController@list'); $router->get('/project-issues/{where}/{val}', 'ProjectIssuesController@customWhere'); + $router->get('/kanban-board/list', 'KanbanBoardController@list'); + $router->post('/kanban-board/add', 'KanbanBoardController@add'); + $router->put('/kanban-board/update/{id}', 'KanbanBoardController@update'); + $router->delete('/kanban-board/delete/{id}', 'KanbanBoardController@delete'); + $router->post('/kanban-board/search', 'KanbanBoardController@search'); + + $router->get('/kanban-card/get-data/{project_id}/{gantt_id}/{board_id}', 'KanbanCardController@getData'); + $router->post('/kanban-card/add', 'KanbanCardController@add'); + $router->put('/kanban-card/update/{id}', 'KanbanCardController@update'); + $router->delete('/kanban-card/delete/{id}', 'KanbanCardController@delete'); + $router->post('/kanban-card/search', 'KanbanCardController@search'); + $router->post('/project-risks/add', 'ProjectRisksController@add'); $router->get('/project-risks/edit/{id}', 'ProjectRisksController@edit'); $router->put('/project-issues/update/{id}', 'ProjectRisksController@update'); @@ -464,7 +476,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/user-to-proyek/edit/{id}', 'UserToProyekController@edit'); $router->put('/user-to-proyek/update/{id}', 'UserToProyekController@update'); $router->post('/user-to-proyek/search', 'UserToProyekController@search'); - $router->delete('/user-to-proyek/delete/{id}', 'UserToProyekController@delete'); + $router->delete('/user-to-proyek/delete/{id}/{company_id}', 'UserToProyekController@delete'); $router->get('/user-to-proyek/list', 'UserToProyekController@list'); $router->get('/user-to-proyek/select', 'UserToProyekController@select'); $router->get('/user-to-proyek/get-employee-integration', 'UserToProyekController@getEmployeeIntegration'); From 55fcde723d06cb57b184136fe5015ea3244727dc Mon Sep 17 00:00:00 2001 From: wahyun Date: Mon, 19 Feb 2024 17:04:36 +0700 Subject: [PATCH 092/155] add limits user --- .../Controllers/HumanResourceController.php | 42 +++++++++++++++---- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index 9b46c9b..acffb77 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -41,7 +41,7 @@ class HumanResourceController extends Controller ->where('company_id', $request->company_id) ->first(); if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { - if($projectResult['total_hr'] < 10) { + if($projectResult['total_hr'] < 50) { $countCreate = true; } } elseif ($cloneQueryTransaction->where([['type_paket','Free'],['amount',0]])->exists()) { @@ -74,7 +74,7 @@ class HumanResourceController extends Controller 'employee_type' => 'required', 'company_id' => 'required', 'username' => 'required', - 'email' => 'required' + 'email' => 'required|unique:m_users,email|email' ]); $data = $request->all(); @@ -113,10 +113,38 @@ class HumanResourceController extends Controller { if (!$id || (int) $id < 0 || $id == "") { - return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + return response()->json(['status' => 'failed', 'message' => 'Id is required!', 'code' => 400], 400); } $humanresource = HumanResource::find($id); + if(empty($humanresource)) { + return response()->json(['status' => 'failed', 'message' => 'Data Human Resource not found!', 'code' => 400], 400); + } + $transaction = ProductTransaction::query() + ->where('company_id', $request->company_id); + $cloneQueryTransaction = clone $transaction; + if($request->company_id && isset($request->password) && isset($request->username)) : + $countCreate = false; + $projectResult = HumanResource::query() + ->selectRaw('count(*) as total_hr') + ->where([ + ['company_id', $request->company_id], + ['username', '!=', null], + ['password', '!=', null] + ]) + ->first(); + if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { + if($projectResult['total_hr'] < 10) { + $countCreate = true; + } + } elseif ($cloneQueryTransaction->where([['type_paket','Free'],['amount',0]])->exists()) { + if($projectResult['total_hr'] < 1) { + $countCreate = true; + } + } else { + $countCreate = true; + } + endif; $request->ktp_number !== $humanresource['ktp_number'] ? $this->validate($request,['ktp_number'=>'unique:m_users,ktp_number|string']) : ''; $request->email !== $humanresource['email'] ? $this->validate($request,['email'=>'unique:m_users,email|email']) : ''; $request->password ? $this->validate($request,['password'=>'required|min:8']) : ''; @@ -131,11 +159,10 @@ class HumanResourceController extends Controller return response()->json(['status' => 'failed', 'message' => 'Username already exists!', 'code' => 400], 400); } - if ($humanresource) { + if ($countCreate) { $result = $humanresource->update($data); - } else { - return response()->json(['status' => 'failed', 'message' => 'data Human Resource Pool not found!', 'code' => 400], 400); - die(); + } else { + return response()->json(['status' => 'failed', 'message' => 'Limited to create human resource!', 'code' => 500], 500); } if ($result) { @@ -153,7 +180,6 @@ class HumanResourceController extends Controller $delete = $data->delete(); } else { return response()->json(['status' => 'failed', 'message' => 'data Human Resource Pool not found!', 'code' => 400], 400); - die(); } From d38f1f898e423eb74de9a7671ba32ae05b808144 Mon Sep 17 00:00:00 2001 From: wahyun Date: Mon, 19 Feb 2024 17:04:59 +0700 Subject: [PATCH 093/155] add kanban feature --- .../Controllers/KanbanBoardController.php | 115 ++++++++ app/Http/Controllers/KanbanCardController.php | 258 ++++++++++++++++++ app/Models/KanbanBoard.php | 17 ++ app/Models/KanbanCard.php | 17 ++ 4 files changed, 407 insertions(+) create mode 100644 app/Http/Controllers/KanbanBoardController.php create mode 100644 app/Http/Controllers/KanbanCardController.php create mode 100644 app/Models/KanbanBoard.php create mode 100644 app/Models/KanbanCard.php diff --git a/app/Http/Controllers/KanbanBoardController.php b/app/Http/Controllers/KanbanBoardController.php new file mode 100644 index 0000000..fe8504e --- /dev/null +++ b/app/Http/Controllers/KanbanBoardController.php @@ -0,0 +1,115 @@ +validate($request, [ + 'name_board' => 'required', + 'header_color' => 'required', + 'body_color' => 'required', + 'proyek_id' => 'required', + 'version_gantt_id' => 'required', + 'status_progress' => 'required' + ]); + $data = $request->all(); + $data['created_by'] = $this->currentName; + $statusCount = KanbanBoard::where('version_gantt_id', $request->version_gantt_id) + ->where('status_progress', $request->status_progress) + ->get() + ->count(); + + if ($statusCount < 1 || $request->status_progress == 'none') { + $result = KanbanBoard::create($data); + } else { + return response()->json(['status'=>'failed','message'=>'Board kanban failed created','code'=>400], 400); + } + + if($result){ + return response()->json(['status'=>'success','message'=>'Board kanban successfull created','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Board kanban failed created','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 = KanbanBoard::find($id); + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'Data Board kanban not found!','code'=>400], 400); + die(); + } + + if($result){ + return response()->json(['status'=>'success','message'=>'Board kanban successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Board kanban failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = KanbanBoard::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'Data Board kanban not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'Board kanban successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Board kanban 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 = KanbanBoard::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data Board kanban, please try again later!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'kanban_board'); + $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(Request $request) + { + $query = KanbanBoard::select("*"); + $countData = $query->count(); + $data = $this->paramsMethodGet($query, $countData, $request); + + if($data) + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>count($data)], 200); + + return response()->json(['status'=>'failed','message'=>'failed get Board kanban, please try again later!','code'=>400], 400); + } +} diff --git a/app/Http/Controllers/KanbanCardController.php b/app/Http/Controllers/KanbanCardController.php new file mode 100644 index 0000000..39f9146 --- /dev/null +++ b/app/Http/Controllers/KanbanCardController.php @@ -0,0 +1,258 @@ +where("type_activity", $type_activity) + ->get(); + foreach ($dataActivity as $keyA) { + // $this->add($keyA->id, $gantt_id, $board_id); + $data = array( + 'activity_id' => $keyA->id, + 'kanban_board_id' => $board_id, + 'version_gantt_id' => $gantt_id, + 'created_by' => $this->currentName + ); + switch ($status_progress) { + case 'open': + if ($keyA->persentase_progress == 0) { + $add = KanbanCard::create($data); + } + break; + case 'on-progress': + if ($keyA->persentase_progress > 0 && $keyA->persentase_progress < 100) { + $cardIds = DB::table('kanban_card as kc') + ->join('m_activity as ma', 'kc.activity_id', '=', 'ma.id') + ->where('kc.activity_id', '=', $keyA->id) + ->select('kc.id') + ->get(); + foreach ($cardIds as $cardId) { + $this->delete($cardId->id); + } + $add = KanbanCard::create($data); + } + break; + case 'done': + if ($keyA->persentase_progress == 100) { + $cardIds = DB::table('kanban_card as kc') + ->join('m_activity as ma', 'kc.activity_id', '=', 'ma.id') + ->where('kc.activity_id', '=', $keyA->id) + ->select('kc.id') + ->get(); + foreach ($cardIds as $cardId) { + $this->delete($cardId->id); + } + $add = KanbanCard::create($data); + } + break; + } + } + return "success"; + } + + 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 = KanbanCard::where("activity_id", $id); + if ($data) { + $result = $data->update($request->all()); + } else { + return response()->json(['status' => 'failed', 'message' => 'Data Card kanban not found!', 'code' => 400], 400); + die(); + } + + $board = KanbanBoard::find($request->kanban_board_id); + $activity = Activity::find($id); + if ($board->status_progress == "done" && $activity) { + $activity->update(['persentase_progress' => 100]); + } else{ + if($activity['persentase_progress'] != 95 && $activity['persentase_progress'] != 100){ + $activity->update(['persentase_progress' => 0]); + }else{ + $activity->update(['persentase_progress' => 95]); + } + + } + + if ($result) { + return response()->json(['status' => 'success', 'message' => 'Board kanban successfully updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Board kanban failed updated!', 'code' => 400], 400); + } + } + + public function delete($id) + { + $data = KanbanCard::find($id); + + if ($data) { + $delete = $data->delete(); + } else { + return response()->json(['status' => 'failed', 'message' => 'Data Board kanban not found!', 'code' => 400], 400); + die(); + } + + + if ($delete) { + return response()->json(['status' => 'success', 'message' => 'Board kanban successfully deleted!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Board kanban 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 = KanbanCard::find($id); + + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get data Board kanban, please try again later!', 'code' => 400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'kanban_board'); + $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 getData($project_id, $gantt_id, $board_id, Request $request) + { + // cek ketika dia owner dari project maka + $SESSIONID = $request->session; + $status_progress = KanbanBoard::select("status_progress")->where('id', $board_id)->first(); + if ($status_progress) { + if (DB::table('user_to_version_gantt')->where('user_id', $SESSIONID)->where('version_gantt_id', $gantt_id)->exists()) { + $dataCard = $this->getDataAll($project_id, $gantt_id, $board_id, $status_progress->status_progress, true); + } else { + $dataCard = $this->getDataContributor($project_id, $gantt_id, $board_id, $request, $status_progress->status_progress, true); + } + } else { + return response()->json(['status' => 'empty', 'message' => 'data board is empty, please you insert!', 'code' => 200], 200); + } + + if ($dataCard && count($dataCard) > 0){ + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataCard, "totalRecord" => count($dataCard)], 200); + }else{ + return response()->json(['status' => 'empty', 'message' => 'data card is empty, please you insert!', 'code' => 200], 200); + } + + } + + private function getDataAll($project_id, $gantt_id, $board_id, $status_progress, $status) + { + $dataFinal = []; + if($status == true){ + if ($status_progress != 'none') { + if (KanbanCard::where('kanban_board_id', $board_id)->where("version_gantt_id", $gantt_id)->count() == 0) { + $this->add($board_id, $gantt_id, 'task', $status_progress); + $this->getDataAll($project_id, $gantt_id, $board_id, $status_progress, false); + } + } + } + + $dataCard = DB::table("kanban_card as kc") + ->select("ma.id as activity_id", "ma.name", "ma.start_date", "ma.end_date", "ma.persentase_bobot", "ma.jumlah_pekerjaan", "ma.bobot_planning", "ma.persentase_progress") + ->join("m_activity as ma", "ma.id", "=", "kc.activity_id") + ->where("kc.kanban_board_id", $board_id) + ->where("kc.version_gantt_id", $gantt_id) + ->orderBy('ma.sortorder') + ->get(); + + foreach ($dataCard as $keyCard) { + $query = DB::table("assign_hr_to_activity as ahta") + ->select("ahta.id", "mu.name", "mu.id as id_hr") + ->join("m_users as mu", "mu.id", "=", "ahta.user_id") + ->where("ahta.activity_id", $keyCard->activity_id) + ->get(); + + $dataArray = array( + "id" => $keyCard->activity_id, + "assign_hr" => $query, + "activity" => $keyCard->name, + "start_date" => $keyCard->start_date, + "end_date" => $keyCard->end_date, + "jumlah_pekerjaan" => $keyCard->jumlah_pekerjaan, + "bobot_planning" => $keyCard->bobot_planning, + "persentase_progress" => $keyCard->persentase_progress + ); + $dataFinal[] = $dataArray; + } + // } + return $dataFinal; + } + + private function getDataContributor($project_id, $gantt_id, $board_id, $request, $status_progress, $status) + { + $dataFinal = []; + if($status == true){ + if ($status_progress != 'none') { + if (KanbanCard::where('kanban_board_id', $board_id)->where("version_gantt_id", $gantt_id)->count() == 0) { + $this->add($board_id, $gantt_id, 'task', $status_progress); + $this->getDataContributor($project_id, $gantt_id, $board_id, $request, $status_progress, false); + } + } + $dataUser = User::whereId($request->session)->first(); + $dataCard = DB::table("kanban_card as kc") + ->select("ma.id as activity_id", "ma.name", "ma.start_date", "ma.end_date", "ma.persentase_bobot", "ma.jumlah_pekerjaan", "ma.bobot_planning", "ma.persentase_progress") + ->join("m_activity as ma", "ma.id", "=", "kc.activity_id") + ->where([ + ["kc.created_by", $dataUser['name']], + ["kc.kanban_board_id", $board_id], + ["kc.version_gantt_id", $gantt_id] + ]) + ->orderBy('ma.sortorder') + ->get(); + foreach ($dataCard as $keyCard) { + $query = DB::table("assign_hr_to_activity as ahta") + ->select("ahta.id", "mu.name", "mu.id as id_hr") + ->join("m_users as mu", "mu.id", "=", "ahta.user_id") + ->where("ahta.activity_id", $keyCard->activity_id) + ->get(); + + $dataArray = array( + "id" => $keyCard->activity_id, + "assign_hr" => $query, + "activity" => $keyCard->name, + "start_date" => $keyCard->start_date, + "end_date" => $keyCard->end_date, + "jumlah_pekerjaan" => $keyCard->jumlah_pekerjaan, + "bobot_planning" => $keyCard->bobot_planning, + "persentase_progress" => $keyCard->persentase_progress, + "test" => $request->session + ); + $dataFinal[] = $dataArray; + } + } + + return $dataFinal; + } + +} diff --git a/app/Models/KanbanBoard.php b/app/Models/KanbanBoard.php new file mode 100644 index 0000000..f6a6918 --- /dev/null +++ b/app/Models/KanbanBoard.php @@ -0,0 +1,17 @@ + Date: Tue, 20 Feb 2024 16:03:19 +0700 Subject: [PATCH 094/155] add fillable company_id --- app/Models/Satuan.php | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/app/Models/Satuan.php b/app/Models/Satuan.php index 05305af..bec1ec5 100644 --- a/app/Models/Satuan.php +++ b/app/Models/Satuan.php @@ -1,17 +1,17 @@ - Date: Wed, 21 Feb 2024 13:47:32 +0700 Subject: [PATCH 095/155] add refferalController --- .../Controllers/RefferalCodeController.php | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 app/Http/Controllers/RefferalCodeController.php diff --git a/app/Http/Controllers/RefferalCodeController.php b/app/Http/Controllers/RefferalCodeController.php new file mode 100644 index 0000000..65a3e3b --- /dev/null +++ b/app/Http/Controllers/RefferalCodeController.php @@ -0,0 +1,81 @@ +validate($request, [ + 'code' => 'required|unique:refferal_code,code', + 'exp' => 'nullable', + 'type' => 'nullable', + 'allocation' => 'nullable' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = RefferalCode::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'Add refferal code successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Add refferal Code 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 = RefferalCode::find($id); + + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Failed get refferal code, 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 = RefferalCode::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'Refferal code not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'Refferal code successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Refferal code failed updated!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'refferal_code'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); + } +} From d8c9437671d9800794733e99a27be13e7cf8722a Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 21 Feb 2024 13:48:22 +0700 Subject: [PATCH 096/155] add refferal method & endpoint --- app/Http/Controllers/RoleMenuController.php | 37 +++++++++++++++++++++ routes/web.php | 7 ++++ 2 files changed, 44 insertions(+) diff --git a/app/Http/Controllers/RoleMenuController.php b/app/Http/Controllers/RoleMenuController.php index ebd5d0a..ea25f3e 100644 --- a/app/Http/Controllers/RoleMenuController.php +++ b/app/Http/Controllers/RoleMenuController.php @@ -28,6 +28,43 @@ class RoleMenuController extends Controller } } + public function addMultiple(Request $request) + { + $menus = $request->all(); + + if (is_array($menus) && count($menus) > 0 && isset($menus[0]['menu_id'])) { + $countRes = 0; + foreach ($menus as $menu) { + + $dataInsert = array( + "menu_id" => $menu['menu_id'], + "role_id" => $menu['role_id'], + ); + + $result = RoleMenu::create($dataInsert); + + if ($result) { + $countRes++; + } else { + $countRes--; + } + } + + if ($countRes > 0) { + return response()->json(['status' => 'success', 'message' => 'Add data menu role successfully!', 'code' => 200]); + } else { + return response()->json(['status' => 'failed', 'message' => 'Add data menu role failed created!', 'code' => 500]); + } + } else { + if(isset($data)) + { + return response()->json(['status' => 'success', 'message' => 'Add data menu role successfully!', 'code' => 200]); + }else{ + return response()->json(['status' => 'failed', 'message' => 'Add data menu role failed created!', 'code' => 500]); + } + } + } + public function update(Request $request, $id) { if(!$id || (int) $id < 0 || $id==""){ diff --git a/routes/web.php b/routes/web.php index 19a4bd4..2834452 100644 --- a/routes/web.php +++ b/routes/web.php @@ -16,6 +16,8 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/demo-management-user/add', 'DemoController@add'); $router->post('/role-user/add', 'RoleController@add'); $router->post('/menu-company-user/add-multiple', 'MenuCompanyController@addMultiple'); + $router->post('/role-menu-user/add-multiple', 'RoleMenuController@addMultiple'); + $router->post('/refferal-code/search', 'RefferalCodeController@search'); $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); @@ -133,6 +135,11 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/human-resource/check-old-password/{id}', 'HumanResourceController@checkOldPassword'); $router->get('/human-resource/sync', 'HumanResourceController@sync'); + $router->post('/refferal-code/search', 'RefferalCodeController@search'); + $router->post('/refferal-code/add', 'RefferalCodeController@add'); + $router->get('/refferal-code/edit/{id}', 'RefferalCodeController@edit'); + $router->put('/refferal-code/update/{id}', 'RefferalCodeController@update'); + $router->post('/project-role/search', 'ProjectRoleController@search'); $router->post('/project-role/add', 'ProjectRoleController@add'); $router->get('/project-role/edit/{id}', 'ProjectRoleController@edit'); From c656ed26e16073bc1e6253af1ad322bf03204c35 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 21 Feb 2024 13:48:38 +0700 Subject: [PATCH 097/155] add refferal models --- app/Models/RefferalCode.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 app/Models/RefferalCode.php diff --git a/app/Models/RefferalCode.php b/app/Models/RefferalCode.php new file mode 100644 index 0000000..8046efc --- /dev/null +++ b/app/Models/RefferalCode.php @@ -0,0 +1,29 @@ + Date: Thu, 22 Feb 2024 16:59:52 +0700 Subject: [PATCH 098/155] add discount_id --- app/Models/Company.php | 3 +- app/Models/User.php | 79 ++++++++++++++++++++---------------------- 2 files changed, 39 insertions(+), 43 deletions(-) diff --git a/app/Models/Company.php b/app/Models/Company.php index 85e5868..86d97fd 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -34,6 +34,7 @@ class Company extends Model 'updated_by', 'cluster', 'type_account', - 'date_register' + 'date_register', + 'discount_id' ]; } diff --git a/app/Models/User.php b/app/Models/User.php index d6fe343..fe591b3 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -11,7 +11,7 @@ use Illuminate\Database\Eloquent\Model; use Laravel\Lumen\Auth\Authorizable; use Carbon\Carbon; -class User extends Model implements AuthenticatableContract, AuthorizableContract,JWTSubject +class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject { use Authenticatable, Authorizable, HasFactory; @@ -24,7 +24,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac protected $fillable = [ 'name', 'email', 'role_id', 'username', 'session_login', 'phone_number', 'email', 'address', 'fcm_token', 'gender', 'birth_place', 'birth_date', 'blood_type', 'ktp_number', 'working_hours', - 'created_at', 'created_by', 'updated_at', 'updated_by', 'status_resource' + 'created_at', 'created_by', 'updated_at', 'updated_by', 'status_resource', 'discount_id' ]; const CREATED_AT = 'created_at'; @@ -71,44 +71,42 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac * @return array of carbon or NULL in case HOLIDAY */ - public function getWorkingTime(Carbon $ts, $f = "08:00", $t = "17:00", $tz = self::DEFAULT_TZ) + public function getWorkingTime(Carbon $ts, $f = "08:00", $t = "17:00", $tz = self::DEFAULT_TZ) { $workingTime = array( - "from"=> Carbon::createFromTimeString($f, $tz), - "to"=> Carbon::createFromTimeString($t, $tz) + "from" => Carbon::createFromTimeString($f, $tz), + "to" => Carbon::createFromTimeString($t, $tz) ); - $userShift = UserShift::where('user_id', ) + $userShift = UserShift::where('user_id',) ->orderByDesc('from_date') ->first(); $shift = null; - if ($userShift !== null) - { + if ($userShift !== null) { $shiftId = null; - switch ($ts->shortEnglishDayOfWeek) - { - case "Mon": - $shiftId = $userShift->mon_shift_id; - break; - case "Tue": - $shiftId = $userShift->tue_shift_id; - break; - case "Wed": - $shiftId = $userShift->wed_shift_id; - break; - case "Thu": - $shiftId = $userShift->thu_shift_id; - break; - case "Fri": - $shiftId = $userShift->fri_shift_id; - break; - case "Sat": - $shiftId = $userShift->sat_shift_id; - break; - case "Sun": - $shiftId = $userShift->sun_shift_id; - break; + switch ($ts->shortEnglishDayOfWeek) { + case "Mon": + $shiftId = $userShift->mon_shift_id; + break; + case "Tue": + $shiftId = $userShift->tue_shift_id; + break; + case "Wed": + $shiftId = $userShift->wed_shift_id; + break; + case "Thu": + $shiftId = $userShift->thu_shift_id; + break; + case "Fri": + $shiftId = $userShift->fri_shift_id; + break; + case "Sat": + $shiftId = $userShift->sat_shift_id; + break; + case "Sun": + $shiftId = $userShift->sun_shift_id; + break; } if ($shiftId === null) { @@ -123,8 +121,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac } - if ($shift !== null) - { + if ($shift !== null) { $from = Carbon::createFromTimeString($shift->start_time, $tz) ->subMinutes($shift->flex_time_minute); $to = Carbon::createFromTimeString($shift->end_time, $tz) @@ -146,20 +143,18 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac /** * Get presence status */ - public function presenceStatus(Carbon $at = null, $tz = self::DEFAULT_TZ) + public function presenceStatus(Carbon $at = null, $tz = self::DEFAULT_TZ) { $ts = $at; - if ($at !== null) - { + if ($at !== null) { $ts = Carbon::now($tz); } $tsSec = $ts->secondsSinceMidnight(); $status = ""; $wt = $this->getWorkingTime($ts, $tz); - if ($wt === null) - { + if ($wt === null) { $status = self::HOLIDAY; } else { $from = $wt->from; @@ -168,7 +163,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac $tsTo = $to->secondsSinceMidnight(); if ($from->greaterThan($to)) { - $tsMid = 24*60*60 - $tsFrom; + $tsMid = 24 * 60 * 60 - $tsFrom; if ($tsSec >= $tsFrom || $tsSec < $tsTo) { $status = self::INSIDE; } else { @@ -194,10 +189,10 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac } return array( - "status"=>$status, - "ts" => $ts, + "status" => $status, + "ts" => $ts, "clock_in" => $clockIn, "clock_out" => $clockOut ); - } + } } From e735c33734055e405f6d70a0aef6ef42fb8421b8 Mon Sep 17 00:00:00 2001 From: farhantock Date: Thu, 22 Feb 2024 19:34:24 +0700 Subject: [PATCH 099/155] storage Information --- app/Http/Controllers/Controller.php | 42 +++++++++++++++++--------- routes/web.php | 46 +++++++++++++++-------------- 2 files changed, 52 insertions(+), 36 deletions(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 33046be..4380b15 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -13,6 +13,8 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Http; use Laravel\Lumen\Routing\Controller as BaseController; +use RecursiveIteratorIterator; +use RecursiveDirectoryIterator; class Controller extends BaseController { @@ -41,10 +43,10 @@ class Controller extends BaseController protected function setCustomeDirectoryUpload($company_name) { - $pathImage = 'assets/'.$company_name.'/image/'; - $pathDocument = 'assets/'.$company_name.'/file/project/'; - $pathTmpImport = 'assets/'.$company_name.'/file/tmpimport/'; - $pathActivityDocument = 'assets/'.$company_name.'/file/activity/'; + $pathImage = 'assets/' . $company_name . '/image/'; + $pathDocument = 'assets/' . $company_name . '/file/project/'; + $pathTmpImport = 'assets/' . $company_name . '/file/tmpimport/'; + $pathActivityDocument = 'assets/' . $company_name . '/file/activity/'; return [ 'pathImage' => $pathImage, @@ -54,7 +56,19 @@ class Controller extends BaseController ]; } - protected function setLimitsStorage($company, $dokumen, $name, $initPath, $destinatePath) { + public function storage($company_name) + { + $directory = 'assets/' . urldecode($company_name); + + $size = 0; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) { + $size += $file->getSize(); + } + return round($size / 1048576, 2); + } + + protected function setLimitsStorage($company, $dokumen, $name, $initPath, $destinatePath) + { $totalSize = 0; $sizeFile = $dokumen->getSize(); // Path @@ -63,11 +77,11 @@ class Controller extends BaseController $folderPathTmpImport = $destinatePath['pathTmpImport']; $folderPathActivityDocument = $destinatePath['pathActivityDocument']; // Create Directory - if(!file_exists($initPath)) { + if (!file_exists($initPath)) { mkdir($initPath, 0777, true); } // Scanning & Existing Folder - if(file_exists($folderPathImage)) { + if (file_exists($folderPathImage)) { $files = scandir($folderPathImage); foreach ($files as $file) { if (is_file($folderPathImage . '/' . $file)) { @@ -75,7 +89,7 @@ class Controller extends BaseController } } } - if(file_exists($folderPath)) { + if (file_exists($folderPath)) { $filesImage = scandir($folderPath); foreach ($filesImage as $file) { if (is_file($folderPath . '/' . $file)) { @@ -83,7 +97,7 @@ class Controller extends BaseController } } } - if(file_exists($folderPathTmpImport)) { + if (file_exists($folderPathTmpImport)) { $filesTmpImport = scandir($folderPathTmpImport); foreach ($filesTmpImport as $file) { if (is_file($folderPathTmpImport . '/' . $file)) { @@ -91,7 +105,7 @@ class Controller extends BaseController } } } - if(file_exists($folderPathActivityDocument)) { + if (file_exists($folderPathActivityDocument)) { $filesActivityDocument = scandir($folderPathActivityDocument); foreach ($filesActivityDocument as $file) { if (is_file($folderPathActivityDocument . '/' . $file)) { @@ -105,16 +119,16 @@ class Controller extends BaseController ->where('company_id', $company['id']); $cloneQueryTransaction = clone $transaction; $countCreate = false; - if($transaction->where([['type_paket','Basic'], ['amount','!=',null]])->exists()) { + if ($transaction->where([['type_paket', 'Basic'], ['amount', '!=', null]])->exists()) { $maximumSize = 500 * 1024 * 1024; $countCreate = true; - } elseif ($cloneQueryTransaction->where([['type_paket','Free'], ['amount', 0]])->exists()) { + } elseif ($cloneQueryTransaction->where([['type_paket', 'Free'], ['amount', 0]])->exists()) { $maximumSize = 50 * 1024 * 1024; $countCreate = true; } - if($countCreate) { + if ($countCreate) { if ($totalSize > $maximumSize) { - return response()->json(['status'=>'failed','message'=>'Limited storage maximum!','code'=> 500], 500); + return response()->json(['status' => 'failed', 'message' => 'Limited storage maximum!', 'code' => 500], 500); } } $resultMove = $dokumen->move($folderPath, $name); diff --git a/routes/web.php b/routes/web.php index 2834452..b2d7b20 100644 --- a/routes/web.php +++ b/routes/web.php @@ -6,18 +6,18 @@ $router->get('/', function () use ($router) { $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($router) { $router->post('/login', 'AuthController@login'); - // Landing Route + // Landing Route $router->post('/send-email', 'AuthController@sendEmail'); - $router->post('/company-management-user/add', 'CompanyController@add'); - $router->post('/product-transaction/add','ProductTransactionController@add'); - $router->post('/company-management-user/search', 'CompanyController@search'); - $router->post('/human-resource-user/add', 'HumanResourceController@add_user'); - $router->get('/company-management-user/edit/{id}', 'CompanyController@edit'); - $router->post('/demo-management-user/add', 'DemoController@add'); - $router->post('/role-user/add', 'RoleController@add'); - $router->post('/menu-company-user/add-multiple', 'MenuCompanyController@addMultiple'); - $router->post('/role-menu-user/add-multiple', 'RoleMenuController@addMultiple'); - $router->post('/refferal-code/search', 'RefferalCodeController@search'); + $router->post('/company-management-user/add', 'CompanyController@add'); + $router->post('/product-transaction/add', 'ProductTransactionController@add'); + $router->post('/company-management-user/search', 'CompanyController@search'); + $router->post('/human-resource-user/add', 'HumanResourceController@add_user'); + $router->get('/company-management-user/edit/{id}', 'CompanyController@edit'); + $router->post('/demo-management-user/add', 'DemoController@add'); + $router->post('/role-user/add', 'RoleController@add'); + $router->post('/menu-company-user/add-multiple', 'MenuCompanyController@addMultiple'); + $router->post('/role-menu-user/add-multiple', 'RoleMenuController@addMultiple'); + $router->post('/refferal-code/search', 'RefferalCodeController@search'); $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); @@ -78,7 +78,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->delete('/project/delete/{id}/{company_id}', 'ProjectController@delete'); $router->get('/project/list', 'ProjectController@list'); $router->get('/project/set-baseline/{gantt_id}', 'ProjectController@setBaseline'); - $router->get('/project/set-baseline-activity/{activity_id}/{gantt_id}', 'ProjectController@setBaselineActivity'); + $router->get('/project/set-baseline-activity/{activity_id}/{gantt_id}', 'ProjectController@setBaselineActivity'); $router->get('/project/synchronize-report/{gantt_id}', 'ProjectController@synchronizeReport'); $router->get('/project/manpower/{proyek_id}', 'ProjectController@getManpower'); $router->get('/project/manpower/assigned/{gantt_id}', 'ProjectController@getAssignedHR'); @@ -369,17 +369,17 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/project-issues/list', 'ProjectIssuesController@list'); $router->get('/project-issues/{where}/{val}', 'ProjectIssuesController@customWhere'); - $router->get('/kanban-board/list', 'KanbanBoardController@list'); - $router->post('/kanban-board/add', 'KanbanBoardController@add'); - $router->put('/kanban-board/update/{id}', 'KanbanBoardController@update'); - $router->delete('/kanban-board/delete/{id}', 'KanbanBoardController@delete'); - $router->post('/kanban-board/search', 'KanbanBoardController@search'); + $router->get('/kanban-board/list', 'KanbanBoardController@list'); + $router->post('/kanban-board/add', 'KanbanBoardController@add'); + $router->put('/kanban-board/update/{id}', 'KanbanBoardController@update'); + $router->delete('/kanban-board/delete/{id}', 'KanbanBoardController@delete'); + $router->post('/kanban-board/search', 'KanbanBoardController@search'); - $router->get('/kanban-card/get-data/{project_id}/{gantt_id}/{board_id}', 'KanbanCardController@getData'); - $router->post('/kanban-card/add', 'KanbanCardController@add'); - $router->put('/kanban-card/update/{id}', 'KanbanCardController@update'); - $router->delete('/kanban-card/delete/{id}', 'KanbanCardController@delete'); - $router->post('/kanban-card/search', 'KanbanCardController@search'); + $router->get('/kanban-card/get-data/{project_id}/{gantt_id}/{board_id}', 'KanbanCardController@getData'); + $router->post('/kanban-card/add', 'KanbanCardController@add'); + $router->put('/kanban-card/update/{id}', 'KanbanCardController@update'); + $router->delete('/kanban-card/delete/{id}', 'KanbanCardController@delete'); + $router->post('/kanban-card/search', 'KanbanCardController@search'); $router->post('/project-risks/add', 'ProjectRisksController@add'); $router->get('/project-risks/edit/{id}', 'ProjectRisksController@edit'); @@ -587,5 +587,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/demo-management/search', 'DemoController@search'); $router->delete('/demo-management/delete/{id}', 'DemoController@delete'); $router->get('/demo-management/list', 'DemoController@list'); + + $router->get('information-storage/{company_name}', 'Controller@storage'); }); }); From 233a7720adc2e1e24a061232405c9d7fdf704198 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Fri, 23 Feb 2024 13:32:09 +0700 Subject: [PATCH 100/155] update HRController --- app/Http/Controllers/HumanResourceController.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index acffb77..27fa833 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -119,11 +119,11 @@ class HumanResourceController extends Controller if(empty($humanresource)) { return response()->json(['status' => 'failed', 'message' => 'Data Human Resource not found!', 'code' => 400], 400); } - $transaction = ProductTransaction::query() - ->where('company_id', $request->company_id); - $cloneQueryTransaction = clone $transaction; - if($request->company_id && isset($request->password) && isset($request->username)) : + if($request->company_id && isset($request->password) && isset($request->username)) { + $transaction = ProductTransaction::query() + ->where('company_id', $request->company_id); + $cloneQueryTransaction = clone $transaction; $countCreate = false; $projectResult = HumanResource::query() ->selectRaw('count(*) as total_hr') @@ -144,7 +144,9 @@ class HumanResourceController extends Controller } else { $countCreate = true; } - endif; + } else { + $countCreate = true; + } $request->ktp_number !== $humanresource['ktp_number'] ? $this->validate($request,['ktp_number'=>'unique:m_users,ktp_number|string']) : ''; $request->email !== $humanresource['email'] ? $this->validate($request,['email'=>'unique:m_users,email|email']) : ''; $request->password ? $this->validate($request,['password'=>'required|min:8']) : ''; From 263ed94ab4c99c42ff935d31caafba3a323894d7 Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 27 Feb 2024 10:48:41 +0700 Subject: [PATCH 101/155] Contact Sales --- .../Controllers/ContactSalesController.php | 115 ++++++++++++++++++ app/Models/ContactSales.php | 27 ++++ 2 files changed, 142 insertions(+) create mode 100644 app/Http/Controllers/ContactSalesController.php create mode 100644 app/Models/ContactSales.php diff --git a/app/Http/Controllers/ContactSalesController.php b/app/Http/Controllers/ContactSalesController.php new file mode 100644 index 0000000..bfe4521 --- /dev/null +++ b/app/Http/Controllers/ContactSalesController.php @@ -0,0 +1,115 @@ +validate($request, [ + 'name' => 'required', + 'role' => 'required', + 'email' => 'required', + 'number_phone' => 'required', + 'status' => 'required', + ]); + + $data = $request->all(); + + $data['created_by'] = '@System'; + $data['status'] = 'New Request'; + + $result = ContactSales::create($data); + + if ($result) { + return response()->json(['status' => 'success', 'data' => $result, 'message' => 'Your message has been successfully received by our Sales team! Someone from our team will be in touch with you shortly.', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Your message has been 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 = ContactSales::find($id); + + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get data Contact Sales, 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 = ContactSales::find($id); + + + if ($data) { + $result = $data->update($request->all()); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Contact Sales not found!', 'code' => 400], 400); + die(); + } + + + if ($result) { + return response()->json(['status' => 'success', 'message' => 'data Contact Sales successfully updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Contact Sales failed updated!', 'code' => 400], 400); + } + } + + public function delete($id) + { + $data = ContactSales::find($id); + + if ($data) { + $delete = $data->delete(); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Contact Sales not found!', 'code' => 400], 400); + die(); + } + + + if ($delete) { + return response()->json(['status' => 'success', 'message' => 'data Contact Sales successfully deleted!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Contact Sales failed deleted!', 'code' => 400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_contact_sales'); + $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 = ContactSales::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 Contact Sales, please try again later!', 'code' => 400], 400); + } + } +} diff --git a/app/Models/ContactSales.php b/app/Models/ContactSales.php new file mode 100644 index 0000000..9707bb9 --- /dev/null +++ b/app/Models/ContactSales.php @@ -0,0 +1,27 @@ + Date: Tue, 27 Feb 2024 10:49:05 +0700 Subject: [PATCH 102/155] update CURD productTransaction --- .../ProductTransactionController.php | 84 ++++++++++++++++++- app/Models/Demo.php | 1 - 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ProductTransactionController.php b/app/Http/Controllers/ProductTransactionController.php index c5d7a12..9ee9836 100644 --- a/app/Http/Controllers/ProductTransactionController.php +++ b/app/Http/Controllers/ProductTransactionController.php @@ -22,9 +22,91 @@ class ProductTransactionController extends Controller $result = ProductTransaction::create($data); if ($result) { - return response()->json(['status' => 'success','data' => $result, 'message' => 'Add Transaction successfully!', 'code' => 200], 200); + return response()->json(['status' => 'success', 'data' => $result, 'message' => 'Add Transaction successfully!', 'code' => 200], 200); } else { return response()->json(['status' => 'failed', 'message' => 'Add data Transaction 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 = ProductTransaction::find($id); + + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get data Transaction, 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 = ProductTransaction::find($id); + + + if ($data) { + $result = $data->update($request->all()); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Transaction not found!', 'code' => 400], 400); + die(); + } + + + if ($result) { + return response()->json(['status' => 'success', 'message' => 'data Transaction successfully updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Transaction failed updated!', 'code' => 400], 400); + } + } + + public function delete($id) + { + $data = ProductTransaction::find($id); + + if ($data) { + $delete = $data->delete(); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Transaction not found!', 'code' => 400], 400); + die(); + } + + + if ($delete) { + return response()->json(['status' => 'success', 'message' => 'data Transaction successfully deleted!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data Transaction failed deleted!', 'code' => 400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 't_transaction'); + $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 = ProductTransaction::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 Transaction, please try again later!', 'code' => 400], 400); + } + } } diff --git a/app/Models/Demo.php b/app/Models/Demo.php index ded3b3a..7b1f0a1 100644 --- a/app/Models/Demo.php +++ b/app/Models/Demo.php @@ -22,6 +22,5 @@ class Demo extends Model 'created_by', 'updated_at', 'updated_by', - 'company_id' ]; } From 54effe3195a133902b2e406eb49bd58a059fc7df Mon Sep 17 00:00:00 2001 From: farhantock Date: Tue, 27 Feb 2024 10:49:12 +0700 Subject: [PATCH 103/155] update endpoint --- routes/web.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/routes/web.php b/routes/web.php index b2d7b20..76955c6 100644 --- a/routes/web.php +++ b/routes/web.php @@ -33,6 +33,12 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/role-menu/search', 'RoleMenuController@search'); $router->get('/role-menu/get-role/{id}', 'RoleMenuController@listMenu'); + $router->post('/sales-contact/add', 'ContactSalesController@add'); + $router->get('/sales-contact/edit/{id}', 'ContactSalesController@edit'); + $router->put('/sales-contact/update/{id}', 'ContactSalesController@update'); + $router->post('/sales-contact/search', 'ContactSalesController@search'); + $router->delete('/sales-contact/delete/{id}', 'ContactSalesController@delete'); + $router->group(['middleware' => ['auth', 'cors']], function () use ($router) { $router->get('/dashboard/get-company-cashflow/{company_id}/{all_project}/{hierarchy}/{role_name}', 'DashboardBoDController@getCompanyCashFlow'); // project expenditure @@ -589,5 +595,10 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/demo-management/list', 'DemoController@list'); $router->get('information-storage/{company_name}', 'Controller@storage'); + $router->post('/product-transaction/edit/{id}', 'ProductTransactionController@add'); + $router->put('/product-transaction/update/{id}', 'ProductTransactionController@update'); + $router->post('/product-transaction/search', 'ProductTransactionController@search'); + $router->delete('/product-transaction/delete/{id}', 'ProductTransactionController@delete'); + $router->get('/product-transaction/list', 'ProductTransactionController@list'); }); }); From a0f124f3305dccc577e614e082b9a5c36a4e1c61 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 27 Feb 2024 16:50:52 +0700 Subject: [PATCH 104/155] add response parameter --- app/Http/Controllers/HumanResourceController.php | 2 +- app/Http/Controllers/RefferalCodeController.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index 27fa833..a29c92f 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -168,7 +168,7 @@ class HumanResourceController extends Controller } if ($result) { - return response()->json(['status' => 'success', 'message' => 'Human Resource Pool successfully updated!', 'code' => 200], 200); + return response()->json(['status' => 'success', 'data' => $result, 'message' => 'Human Resource Pool successfully updated!', 'code' => 200], 200); } else { return response()->json(['status' => 'failed', 'message' => 'Human Resource Pool failed updated!', 'code' => 400], 400); } diff --git a/app/Http/Controllers/RefferalCodeController.php b/app/Http/Controllers/RefferalCodeController.php index 65a3e3b..1e89fb4 100644 --- a/app/Http/Controllers/RefferalCodeController.php +++ b/app/Http/Controllers/RefferalCodeController.php @@ -23,7 +23,7 @@ class RefferalCodeController extends Controller $result = RefferalCode::create($data); if($result){ - return response()->json(['status'=>'success','message'=>'Add refferal code successfully!','code'=>200], 200); + return response()->json(['status'=>'success', 'data'=> $result, 'message'=>'Add refferal code successfully!','code'=>200], 200); }else{ return response()->json(['status'=>'failed','message'=>'Add refferal Code failed!','code'=>400], 400); } From eaa8839d614a18414f4fdbcd239ce702de9fc070 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 27 Feb 2024 16:51:17 +0700 Subject: [PATCH 105/155] update setLimitsStorage method --- app/Http/Controllers/Controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 4380b15..e320f72 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -131,7 +131,7 @@ class Controller extends BaseController return response()->json(['status' => 'failed', 'message' => 'Limited storage maximum!', 'code' => 500], 500); } } - $resultMove = $dokumen->move($folderPath, $name); + $resultMove = $dokumen->move($initPath, $name); return [ 'resultMove' => $resultMove From 22e17bdf6dc318ba47a2024303f9c1fcbfa4118e Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 27 Feb 2024 16:51:37 +0700 Subject: [PATCH 106/155] add method --- .../ProductTransactionController.php | 54 ++++++++++++++++++- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ProductTransactionController.php b/app/Http/Controllers/ProductTransactionController.php index c5d7a12..e8d9d9b 100644 --- a/app/Http/Controllers/ProductTransactionController.php +++ b/app/Http/Controllers/ProductTransactionController.php @@ -22,9 +22,59 @@ class ProductTransactionController extends Controller $result = ProductTransaction::create($data); if ($result) { - return response()->json(['status' => 'success','data' => $result, 'message' => 'Add Transaction successfully!', 'code' => 200], 200); + return response()->json(['status' => 'success', 'data' => $result, 'message' => 'Add Transaction successfully!', 'code' => 200], 200); } else { - return response()->json(['status' => 'failed', 'message' => 'Add data Transaction failed!', 'code' => 400], 400); + return response()->json(['status' => 'failed', 'message' => 'Add Transaction 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 = ProductTransaction::find($id); + + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Failed get data transaction, 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 = ProductTransaction::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'Data transaction not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'Data transaction successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Data transaction failed updated!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 't_transaction'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); + } } From 19d22c54365c280dce852f997c5b7e53720b6cd6 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 27 Feb 2024 16:51:59 +0700 Subject: [PATCH 107/155] add fillable --- app/Models/HumanResource.php | 1 + app/Models/RefferalCode.php | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Models/HumanResource.php b/app/Models/HumanResource.php index 0e4731a..e1b3706 100644 --- a/app/Models/HumanResource.php +++ b/app/Models/HumanResource.php @@ -14,6 +14,7 @@ class HumanResource extends Model protected $fillable = [ 'role_id', 'username', + 'discount_id', 'password', 'session_login', 'name', diff --git a/app/Models/RefferalCode.php b/app/Models/RefferalCode.php index 8046efc..c6a61fc 100644 --- a/app/Models/RefferalCode.php +++ b/app/Models/RefferalCode.php @@ -12,7 +12,6 @@ class RefferalCode extends Model const UPDATED_AT = 'updated_at'; protected $fillable = [ - 'id', 'code', 'amount', 'exp', From bb9a69f36f25e4421d620853ef08fd7d46e4cf66 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 27 Feb 2024 16:52:13 +0700 Subject: [PATCH 108/155] add route --- routes/web.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/routes/web.php b/routes/web.php index b2d7b20..7380d51 100644 --- a/routes/web.php +++ b/routes/web.php @@ -9,7 +9,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro // Landing Route $router->post('/send-email', 'AuthController@sendEmail'); $router->post('/company-management-user/add', 'CompanyController@add'); - $router->post('/product-transaction/add', 'ProductTransactionController@add'); + $router->post('/product-transaction-user/add', 'ProductTransactionController@add'); $router->post('/company-management-user/search', 'CompanyController@search'); $router->post('/human-resource-user/add', 'HumanResourceController@add_user'); $router->get('/company-management-user/edit/{id}', 'CompanyController@edit'); @@ -17,7 +17,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/role-user/add', 'RoleController@add'); $router->post('/menu-company-user/add-multiple', 'MenuCompanyController@addMultiple'); $router->post('/role-menu-user/add-multiple', 'RoleMenuController@addMultiple'); - $router->post('/refferal-code/search', 'RefferalCodeController@search'); + $router->post('/refferal-code-user/search', 'RefferalCodeController@search'); $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); @@ -140,6 +140,11 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/refferal-code/edit/{id}', 'RefferalCodeController@edit'); $router->put('/refferal-code/update/{id}', 'RefferalCodeController@update'); + $router->post('/product-transaction/search', 'ProductTransactionController@search'); + $router->post('/product-transaction/add', 'ProductTransactionController@add'); + $router->get('/product-transaction/edit/{id}', 'ProductTransactionController@edit'); + $router->put('/product-transaction/update/{id}', 'ProductTransactionController@update'); + $router->post('/project-role/search', 'ProjectRoleController@search'); $router->post('/project-role/add', 'ProjectRoleController@add'); $router->get('/project-role/edit/{id}', 'ProjectRoleController@edit'); From a9c803a5a4653b92718deb75643232db42f61e27 Mon Sep 17 00:00:00 2001 From: farhantock Date: Wed, 28 Feb 2024 10:16:02 +0700 Subject: [PATCH 109/155] handle when Directory not found --- app/Http/Controllers/Controller.php | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index e320f72..2a59ecd 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -15,6 +15,7 @@ use Illuminate\Support\Facades\Http; use Laravel\Lumen\Routing\Controller as BaseController; use RecursiveIteratorIterator; use RecursiveDirectoryIterator; +use Exception; class Controller extends BaseController { @@ -60,13 +61,25 @@ class Controller extends BaseController { $directory = 'assets/' . urldecode($company_name); + if (!is_dir($directory)) { + return "Directory not found"; + } + $size = 0; - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) { - $size += $file->getSize(); + + + try { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) { + $size += $file->getSize(); + } + } catch (Exception $e) { + return "Error while calculating size: " . $e->getMessage(); } + return round($size / 1048576, 2); } + protected function setLimitsStorage($company, $dokumen, $name, $initPath, $destinatePath) { $totalSize = 0; From 0e228e6e18bfc70f3a519397d8e1722c7daf19b5 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Thu, 29 Feb 2024 16:24:41 +0700 Subject: [PATCH 110/155] handle expired ospro --- app/Http/Controllers/AuthController.php | 63 +++++++++++++++---------- app/Http/Controllers/Controller.php | 22 ++++++++- 2 files changed, 60 insertions(+), 25 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 4f06657..0730cbf 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -28,26 +28,32 @@ class AuthController extends Controller $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); - - $usernameCheck = false; + $usernameCheck = false; $passwordCheck = false; - if (User::where('username', $username)->exists()) - $usernameCheck = true; + if (empty($username) || empty($password)) { + return response()->json(['status' => 'error', 'message' => 'You must fill all the fields'], 400); + } - if (User::where('password', md5($password))->exists()) - $passwordCheck = true; + if (User::where('username', $username)->exists()) { + $usernameCheck = true; + } + if (User::where('password', md5($password))->exists()) { + $passwordCheck = true; + } if ($usernameCheck & $passwordCheck) { - $user = User::where('username', $username)->where('password', md5($password))->first(); + $user = User::where([['username', $username],['password', md5($password)]])->first(); + $checkExpiredOspro = $this->setExpiredTimeOspro($user['company_id']); + if($checkExpiredOspro === false) { + return response()->json(['status' => 'error', 'message' => 'Expired! Please update license!'], 201); + } 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); + } $dataUpdateFcm = array( "fcm_token" => $fcm_token @@ -55,8 +61,9 @@ class AuthController extends Controller $hr = User::find($user->id); - if ($hr) - $hr->update($dataUpdateFcm); + if ($hr) { + $hr->update($dataUpdateFcm); + } } $dataRole = Role::find($user->role_id); @@ -71,21 +78,26 @@ class AuthController extends Controller $configApp->logo_header = $logoHeader; } - if ($configApp) + if ($configApp) { $user->configApp = $configApp; + } - if ($dataRole) + if ($dataRole) { $user->role = $dataRole; + } - if ($dataHierarchy) + if ($dataHierarchy) { $user->hierarchy = $dataHierarchy; + } - if (!$token = Auth::login($user)) + if (!$token = Auth::login($user)) { return response()->json(['error' => 'Unauthorized'], 401); + } $ttl = 60; - if ($remember) + 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)]); */ @@ -101,12 +113,15 @@ class AuthController extends Controller ), ]); } else { - if (!$usernameCheck && !$passwordCheck) - return response()->json(['code' => 201, 'message' => "username and password doesn't match"], 201); - if (!$passwordCheck) - return response()->json(['code' => 201, 'message' => "password doesn't match"], 201); - if (!$usernameCheck) - return response()->json(['code' => 201, 'message' => "username doesn't match"], 201); + if (!$usernameCheck && !$passwordCheck) { + return response()->json(['code' => 201, 'message' => "Username and password doesn't match"], 201); + } + if (!$passwordCheck) { + return response()->json(['code' => 201, 'message' => "Password doesn't match"], 201); + } + if (!$usernameCheck) { + return response()->json(['code' => 201, 'message' => "Username doesn't match"], 201); + } } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index e320f72..f26f623 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -6,11 +6,12 @@ use App\Models\User; use App\Models\Divisi; use App\Models\Activity; use App\Models\AssignMaterial; +use App\Models\Company; use App\Models\ReportK3Detail; use App\Models\UserToActivity; use App\Models\ProductTransaction; use Illuminate\Support\Facades\DB; - +use Carbon\Carbon; use Illuminate\Support\Facades\Http; use Laravel\Lumen\Routing\Controller as BaseController; use RecursiveIteratorIterator; @@ -67,6 +68,25 @@ class Controller extends BaseController return round($size / 1048576, 2); } + public function setExpiredTimeOspro($company_id) + { + $currentDate = Carbon::now(); + $countCreate = false; + $transaction = ProductTransaction::query() + ->where('company_id', $company_id)->first(); + if(!empty($transaction)) { + $dateExpired = $transaction['exp_ospro']; + if ($currentDate->gt(Carbon::parse($dateExpired))) { + $countCreate = false; + } else { + $countCreate = true; + } + return $countCreate; + } else { + return $countCreate; + } + } + protected function setLimitsStorage($company, $dokumen, $name, $initPath, $destinatePath) { $totalSize = 0; From 773f1144040ace45defe9d83bb1263c8ace8af3c Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 6 Mar 2024 16:42:44 +0700 Subject: [PATCH 111/155] update use --- .../Controllers/AssignMaterialController.php | 8 +- .../Controllers/AssignToolsController.php | 319 +++++++++--------- app/Http/Controllers/HolidayController.php | 280 +++++++-------- .../Controllers/ReportActivityController.php | 2 +- .../ReportActivityMaterialController.php | 6 +- .../Controllers/UserToActivityController.php | 2 +- 6 files changed, 310 insertions(+), 307 deletions(-) diff --git a/app/Http/Controllers/AssignMaterialController.php b/app/Http/Controllers/AssignMaterialController.php index e385a95..7a5e9d8 100644 --- a/app/Http/Controllers/AssignMaterialController.php +++ b/app/Http/Controllers/AssignMaterialController.php @@ -8,7 +8,7 @@ use App\Models\RequestMaterial; use App\Models\Activity; use App\Models\ReportActivityMaterial; use Illuminate\Support\Facades\DB; -use Datatables; +use Yajra\Datatables\Datatables; class AssignMaterialController extends Controller { @@ -47,7 +47,11 @@ class AssignMaterialController extends Controller if ($planDate >= $startDate) { $result = AssignMaterial::create($data); - return response()->json(['status' => 'success', 'message' => 'Data added!', 'code' => 200], 200); + if($result) { + return response()->json(['status' => 'success', 'message' => 'Data added!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Failed to add data!', 'code' => 400], 400); + } } else { return response()->json(['status' => 'failed', 'message' => 'Failed to add data!', 'code' => 400], 400); } diff --git a/app/Http/Controllers/AssignToolsController.php b/app/Http/Controllers/AssignToolsController.php index 4e2b2c6..4185991 100644 --- a/app/Http/Controllers/AssignToolsController.php +++ b/app/Http/Controllers/AssignToolsController.php @@ -1,160 +1,159 @@ -validate($request, [ - 'activity_id' => 'required', - 'tools_id' => 'required', - 'qty_planning' => 'required', - ]); - - $checkStock = ToolsResource::where("id", $request->tools_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 = AssignTools::create($data); - if($result){ - $checkStock = ToolsResource::find($request->tools_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 tools success!','code'=>200]); - }else{ - return response()->json(['status'=>'failed','message'=>'Assign tools failed','code'=>400]); - } - } - - private function updateFromAdd($data){ - $assignTools = AssignTools::where("activity_id", $data->activity_id)->where("tools_id", $data->tools_id)->first(); - - $newQty = (int)$assignTools->qty_planning + (int)$data->qty_planning; - $dataUpdate = array( - "qty_planning"=>$newQty, - "updated_by"=>$this->currentName - ); - - $dataWillUpdate = AssignMaterial::where("activity_id", $data->activity_id)->where("tools_id", $data->tools_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 = AssignTools::find($id); - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'Data Assign tools not found!','code'=>400], 400); - die(); - } - - if($result){ - return response()->json(['status'=>'success','message'=>'Assign tools successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Assign tools failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = AssignTools::find($id); - - if($data){ - $id = $data->tools_id; - $stock = $data->qty_planning; - $toolsResource = ToolsResource::find($id); - if($toolsResource){ - $oldStock = $toolsResource->qty; - $newStock = $oldStock + $stock; - $dataUpdate = array( - "qty"=>$newStock, - "updated_by"=>$this->currentName - ); - $toolsResource->update($dataUpdate); - } - - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'Data Assign tools not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'Assign tools successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Assign tools 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 = AssignTools::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 tools, please try again later!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'assign_tools_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 = AssignTools::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 tools, please try again later!','code'=>400], 400); - } - } - - public function datatables(Request $request){ - $id_activity = $request->query('idact'); - $data = AssignTools::select("assign_tools_to_activity.*","m.name as tools_name","m.uom as uom")->join("m_tools_resource as m", "m.id", "=", "assign_tools_to_activity.tools_id")->where('assign_tools_to_activity.activity_id', $id_activity)->get(); - return Datatables::of($data) - ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; - return $actionBtn; - }) - ->rawColumns(['action'])->make(true); - } -} +validate($request, [ + 'activity_id' => 'required', + 'tools_id' => 'required', + 'qty_planning' => 'required', + ]); + + $checkStock = ToolsResource::where("id", $request->tools_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 = AssignTools::create($data); + if($result){ + $checkStock = ToolsResource::find($request->tools_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 tools success!','code'=>200]); + }else{ + return response()->json(['status'=>'failed','message'=>'Assign tools failed','code'=>400]); + } + } + + private function updateFromAdd($data){ + $assignTools = AssignTools::where("activity_id", $data->activity_id)->where("tools_id", $data->tools_id)->first(); + + $newQty = (int)$assignTools->qty_planning + (int)$data->qty_planning; + $dataUpdate = array( + "qty_planning"=>$newQty, + "updated_by"=>$this->currentName + ); + + $dataWillUpdate = AssignMaterial::where("activity_id", $data->activity_id)->where("tools_id", $data->tools_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 = AssignTools::find($id); + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'Data Assign tools not found!','code'=>400], 400); + die(); + } + + if($result){ + return response()->json(['status'=>'success','message'=>'Assign tools successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Assign tools failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = AssignTools::find($id); + + if($data){ + $id = $data->tools_id; + $stock = $data->qty_planning; + $toolsResource = ToolsResource::find($id); + if($toolsResource){ + $oldStock = $toolsResource->qty; + $newStock = $oldStock + $stock; + $dataUpdate = array( + "qty"=>$newStock, + "updated_by"=>$this->currentName + ); + $toolsResource->update($dataUpdate); + } + + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'Data Assign tools not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'Assign tools successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Assign tools 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 = AssignTools::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 tools, please try again later!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'assign_tools_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 = AssignTools::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 tools, please try again later!','code'=>400], 400); + } + } + + public function datatables(Request $request){ + $id_activity = $request->query('idact'); + $data = AssignTools::select("assign_tools_to_activity.*","m.name as tools_name","m.uom as uom")->join("m_tools_resource as m", "m.id", "=", "assign_tools_to_activity.tools_id")->where('assign_tools_to_activity.activity_id', $id_activity)->get(); + return Datatables::of($data) + ->addIndexColumn() + ->addColumn('action', function($row){ + $actionBtn = ''; + return $actionBtn; + }) + ->rawColumns(['action'])->make(true); + } +} diff --git a/app/Http/Controllers/HolidayController.php b/app/Http/Controllers/HolidayController.php index c64fee8..000a925 100644 --- a/app/Http/Controllers/HolidayController.php +++ b/app/Http/Controllers/HolidayController.php @@ -1,140 +1,140 @@ -validate($request, [ - 'proyek_id' => 'required', - 'version_gantt_id' => 'required', - 'date' => 'required' - ]); - - $data = $request->all(); - $duration = $request->duration; - if(!$duration){ - $data['duration'] = 1; - } - $data['created_by'] = $this->currentName; - - $result = Holiday::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'add holiday successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add holiday 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 = Holiday::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data holiday, 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 = Holiday::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data holiday not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data holiday successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data holiday failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = Holiday::find($id); - - if($data){ - $deletedData = $data; - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data holiday not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success', 'data'=>$deletedData,'message'=>'data holiday successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data holiday failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_holidays'); - $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 = Holiday::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 holiday, please try again later!','code'=>400], 400); - } - } - - public function datatables(Request $request){ - $proyek_id = $request->query('proyek_id'); - $gantt_id = $request->query('gantt_id'); - - $data = Holiday::where('proyek_id', $proyek_id)->where('version_gantt_id', $gantt_id)->get(); - - return Datatables::of($data) - ->editColumn('date', function($row) { - $date = date_create($row->date); - $dateFormat = date_format($date,"d-m-Y"); - return $dateFormat; - }) - ->editColumn('duration', function($row) { - $day = (int)$row->duration > 1 ? "days" : "day"; - return $row->duration." ".$day; - }) - ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; - return $actionBtn; - }) - - ->rawColumns(['action'])->make(true); - } -} +validate($request, [ + 'proyek_id' => 'required', + 'version_gantt_id' => 'required', + 'date' => 'required' + ]); + + $data = $request->all(); + $duration = $request->duration; + if(!$duration){ + $data['duration'] = 1; + } + $data['created_by'] = $this->currentName; + + $result = Holiday::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'add holiday successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add holiday 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 = Holiday::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data holiday, 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 = Holiday::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data holiday not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data holiday successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data holiday failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = Holiday::find($id); + + if($data){ + $deletedData = $data; + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data holiday not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success', 'data'=>$deletedData,'message'=>'data holiday successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data holiday failed deleted!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_holidays'); + $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 = Holiday::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 holiday, please try again later!','code'=>400], 400); + } + } + + public function datatables(Request $request){ + $proyek_id = $request->query('proyek_id'); + $gantt_id = $request->query('gantt_id'); + + $data = Holiday::where('proyek_id', $proyek_id)->where('version_gantt_id', $gantt_id)->get(); + + return Datatables::of($data) + ->editColumn('date', function($row) { + $date = date_create($row->date); + $dateFormat = date_format($date,"d-m-Y"); + return $dateFormat; + }) + ->editColumn('duration', function($row) { + $day = (int)$row->duration > 1 ? "days" : "day"; + return $row->duration." ".$day; + }) + ->addIndexColumn() + ->addColumn('action', function($row){ + $actionBtn = ''; + return $actionBtn; + }) + + ->rawColumns(['action'])->make(true); + } +} diff --git a/app/Http/Controllers/ReportActivityController.php b/app/Http/Controllers/ReportActivityController.php index 94a8d89..4607f5c 100644 --- a/app/Http/Controllers/ReportActivityController.php +++ b/app/Http/Controllers/ReportActivityController.php @@ -6,7 +6,7 @@ use Illuminate\Http\Request; use App\Models\ReportActivity; use App\Models\Activity; use App\Models\Image; -use Datatables; +use Yajra\Datatables\Datatables; class ReportActivityController extends Controller { diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index a55e15f..62e08f3 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -8,7 +8,7 @@ use Illuminate\Support\Facades\DB; use App\Models\ReportActivityMaterial; use App\Models\Activity; use App\Models\AssignMaterial; -use Datatables; +use Yajra\Datatables\Datatables; use DateTime; class ReportActivityMaterialController extends Controller @@ -72,10 +72,10 @@ class ReportActivityMaterialController extends Controller // actual < plan $persentaseProgress = $sumReportActivityMaterial/$sumAssignMaterial*100; } - + $dataUpdate = array( "actual_start" => null, - "actual_end" => null, + "actual_end" => null, "persentase_progress" => $persentaseProgress, "updated_by" => $this->currentName ); diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index b6f9926..5313b5d 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -7,7 +7,7 @@ use App\Models\UserToActivity; use App\Models\Activity; use App\Models\AssignMaterial; use Illuminate\Support\Facades\DB; -use Datatables; +use Yajra\Datatables\Datatables; class UserToActivityController extends Controller { From 352c9fc74abb4351619c0ea9ebcc53db871c3be8 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 6 Mar 2024 16:43:12 +0700 Subject: [PATCH 112/155] update unique username --- app/Http/Controllers/HumanResourceController.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index a29c92f..1cbee8b 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -22,7 +22,8 @@ class HumanResourceController extends Controller 'name' => 'required', 'ktp_number' => 'required|string|unique:m_users,ktp_number', 'employee_type' => 'required', - 'company_id' => 'required' + 'company_id' => 'required', + 'username' => 'unique:m_users,username' ]); $data = $request->all(); From 493ebb1cda05c91679b7e50f48dde3988f74f96a Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 6 Mar 2024 16:45:13 +0700 Subject: [PATCH 113/155] update company_id fillable --- app/Models/ProjectRole.php | 34 ++-- app/Models/User.php | 396 ++++++++++++++++++------------------- 2 files changed, 215 insertions(+), 215 deletions(-) diff --git a/app/Models/ProjectRole.php b/app/Models/ProjectRole.php index 52a7b46..f47824c 100644 --- a/app/Models/ProjectRole.php +++ b/app/Models/ProjectRole.php @@ -1,17 +1,17 @@ -getKey(); - } - - /** - * Return a key value array, containing any custom claims to be added to the JWT. - * - * @return array - */ - public function getJWTCustomClaims() - { - return []; - } - - - /** - * Get working hours for given timestamp - * - * @return array of carbon or NULL in case HOLIDAY - */ - - public function getWorkingTime(Carbon $ts, $f = "08:00", $t = "17:00", $tz = self::DEFAULT_TZ) - { - $workingTime = array( - "from" => Carbon::createFromTimeString($f, $tz), - "to" => Carbon::createFromTimeString($t, $tz) - ); - - $userShift = UserShift::where('user_id',) - ->orderByDesc('from_date') - ->first(); - - $shift = null; - if ($userShift !== null) { - $shiftId = null; - switch ($ts->shortEnglishDayOfWeek) { - case "Mon": - $shiftId = $userShift->mon_shift_id; - break; - case "Tue": - $shiftId = $userShift->tue_shift_id; - break; - case "Wed": - $shiftId = $userShift->wed_shift_id; - break; - case "Thu": - $shiftId = $userShift->thu_shift_id; - break; - case "Fri": - $shiftId = $userShift->fri_shift_id; - break; - case "Sat": - $shiftId = $userShift->sat_shift_id; - break; - case "Sun": - $shiftId = $userShift->sun_shift_id; - break; - } - - if ($shiftId === null) { - return null; - } - - $shift = Shift::where('id', $shiftId)->first(); - } else { - $shift = Shift::where('is_non_shift', true) - ->orderByDesc('created_at') - ->first(); - } - - - if ($shift !== null) { - $from = Carbon::createFromTimeString($shift->start_time, $tz) - ->subMinutes($shift->flex_time_minute); - $to = Carbon::createFromTimeString($shift->end_time, $tz) - ->addMinutes($shift->flex_time_minute); - - /* - if ($to->lessThan($from)) - { - $to->addDay(); - } - */ - $workingTime['from'] = $from; - $workingTime['to'] = $to; - } - - return $workingTime; - } - - /** - * Get presence status - */ - public function presenceStatus(Carbon $at = null, $tz = self::DEFAULT_TZ) - { - - $ts = $at; - if ($at !== null) { - $ts = Carbon::now($tz); - } - $tsSec = $ts->secondsSinceMidnight(); - - $status = ""; - $wt = $this->getWorkingTime($ts, $tz); - if ($wt === null) { - $status = self::HOLIDAY; - } else { - $from = $wt->from; - $to = $wt->to; - $tsFrom = $from->secondsSinceMidnight(); - $tsTo = $to->secondsSinceMidnight(); - - if ($from->greaterThan($to)) { - $tsMid = 24 * 60 * 60 - $tsFrom; - if ($tsSec >= $tsFrom || $tsSec < $tsTo) { - $status = self::INSIDE; - } else { - $status = self::OUTSIDE; - } - } else { - if ($tsSec < $tsFrom || $tsSec > $tsTo) { - $status = self::OUTSIDE; - } else { - $status = self::INSIDE; - } - } - } - - $clockIn = null; - $clockOut = null; - $inout = Presence::where('user_id', $this->id) - ->orderByDesc('clock_in') - ->first(); - if ($inout !== null) { - $clockIn = Carbon::parse($inout->clock_in, $tz); - $clockOut = Carbon::parse($inout->clock_out, $tz); - } - - return array( - "status" => $status, - "ts" => $ts, - "clock_in" => $clockIn, - "clock_out" => $clockOut - ); - } -} +getKey(); + } + + /** + * Return a key value array, containing any custom claims to be added to the JWT. + * + * @return array + */ + public function getJWTCustomClaims() + { + return []; + } + + + /** + * Get working hours for given timestamp + * + * @return array of carbon or NULL in case HOLIDAY + */ + + public function getWorkingTime(Carbon $ts, $f = "08:00", $t = "17:00", $tz = self::DEFAULT_TZ) + { + $workingTime = array( + "from" => Carbon::createFromTimeString($f, $tz), + "to" => Carbon::createFromTimeString($t, $tz) + ); + + $userShift = UserShift::where('user_id',) + ->orderByDesc('from_date') + ->first(); + + $shift = null; + if ($userShift !== null) { + $shiftId = null; + switch ($ts->shortEnglishDayOfWeek) { + case "Mon": + $shiftId = $userShift->mon_shift_id; + break; + case "Tue": + $shiftId = $userShift->tue_shift_id; + break; + case "Wed": + $shiftId = $userShift->wed_shift_id; + break; + case "Thu": + $shiftId = $userShift->thu_shift_id; + break; + case "Fri": + $shiftId = $userShift->fri_shift_id; + break; + case "Sat": + $shiftId = $userShift->sat_shift_id; + break; + case "Sun": + $shiftId = $userShift->sun_shift_id; + break; + } + + if ($shiftId === null) { + return null; + } + + $shift = Shift::where('id', $shiftId)->first(); + } else { + $shift = Shift::where('is_non_shift', true) + ->orderByDesc('created_at') + ->first(); + } + + + if ($shift !== null) { + $from = Carbon::createFromTimeString($shift->start_time, $tz) + ->subMinutes($shift->flex_time_minute); + $to = Carbon::createFromTimeString($shift->end_time, $tz) + ->addMinutes($shift->flex_time_minute); + + /* + if ($to->lessThan($from)) + { + $to->addDay(); + } + */ + $workingTime['from'] = $from; + $workingTime['to'] = $to; + } + + return $workingTime; + } + + /** + * Get presence status + */ + public function presenceStatus(Carbon $at = null, $tz = self::DEFAULT_TZ) + { + + $ts = $at; + if ($at !== null) { + $ts = Carbon::now($tz); + } + $tsSec = $ts->secondsSinceMidnight(); + + $status = ""; + $wt = $this->getWorkingTime($ts, $tz); + if ($wt === null) { + $status = self::HOLIDAY; + } else { + $from = $wt->from; + $to = $wt->to; + $tsFrom = $from->secondsSinceMidnight(); + $tsTo = $to->secondsSinceMidnight(); + + if ($from->greaterThan($to)) { + $tsMid = 24 * 60 * 60 - $tsFrom; + if ($tsSec >= $tsFrom || $tsSec < $tsTo) { + $status = self::INSIDE; + } else { + $status = self::OUTSIDE; + } + } else { + if ($tsSec < $tsFrom || $tsSec > $tsTo) { + $status = self::OUTSIDE; + } else { + $status = self::INSIDE; + } + } + } + + $clockIn = null; + $clockOut = null; + $inout = Presence::where('user_id', $this->id) + ->orderByDesc('clock_in') + ->first(); + if ($inout !== null) { + $clockIn = Carbon::parse($inout->clock_in, $tz); + $clockOut = Carbon::parse($inout->clock_out, $tz); + } + + return array( + "status" => $status, + "ts" => $ts, + "clock_in" => $clockIn, + "clock_out" => $clockOut + ); + } +} From 7e74b4434af3304706c3929f197e6d73c69cf583 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 6 Mar 2024 16:45:50 +0700 Subject: [PATCH 114/155] update type data and boot function --- app/Models/Activity.php | 89 ++++++++++++++++++++++------------------- 1 file changed, 47 insertions(+), 42 deletions(-) diff --git a/app/Models/Activity.php b/app/Models/Activity.php index 5d9c1e7..b0c04fa 100644 --- a/app/Models/Activity.php +++ b/app/Models/Activity.php @@ -33,6 +33,9 @@ class Activity extends Model 'jobs_done', 'assign_hr', 'assign_material', 'assign_tools', 'assign_expense' ]; + protected $casts = [ + 'rencana_biaya' => 'double' + ]; public function getStartDateAttribute($value) { @@ -61,58 +64,60 @@ class Activity extends Model public static function boot() { parent::boot(); - - static::updating(function($data) { - $data->logPersentaseProgress(); - }); - - static::updated(function($data) { - $data->updateBobot(); - $data->updateCostPlanning(); - if($data->bobot_planning){ - $data->updatePersentaseProgress(); - } - $data->updateCostActual(); - // if($data->start_date != request()->start_date || $data->end_date != request()->end_date) { - // $data->updateStartEndDateHeader(); - // } - }); - - static::deleted(function($data) { - if (isset($data->parent_id)) { - if(Activity::where("parent_id", $data->parent_id)->count() == 0) { - $activity = Activity::find($data->parent_id); - if ($activity) { - $activity->update(["type_activity"=>"task"]); - } - } - } - - $data->updateBobot(true); - $data->updateCostPlanning(); - if($data->bobot_planning){ - $data->updatePersentaseProgress(); - } - $data->updateCostActual(); - $data->updateStartEndDateHeader(); - }); - + DB::transaction(function() { + static::updating(function($data) { + $data->logPersentaseProgress(); + }); + + static::updated(function($data) { + $data->updateBobot(); + $data->updateCostPlanning(); + if($data->bobot_planning){ + $data->updatePersentaseProgress(); + } + $data->updateCostActual(); + // if($data->start_date != request()->start_date || $data->end_date != request()->end_date) { + // $data->updateStartEndDateHeader(); + // } + }); + + static::deleted(function($data) { + if (isset($data->parent_id)) { + if(Activity::where("parent_id", $data->parent_id)->count() == 0) { + $activity = Activity::find($data->parent_id); + if ($activity) { + $activity->update(["type_activity"=>"task"]); + } + } + } + + $data->updateBobot(true); + $data->updateCostPlanning(); + if($data->bobot_planning){ + $data->updatePersentaseProgress(); + } + $data->updateCostActual(); + $data->updateStartEndDateHeader(); + }); + },5); } private function updateBobot($isDelete = false) { - $root = Activity::where('version_gantt_id', $this->version_gantt_id) - ->where("proyek_id", $this->proyek_id) - ->whereNull('parent_id') + $root = Activity::where([ + ['version_gantt_id', $this->version_gantt_id], + ['proyek_id', $this->proyek_id] + ]) + ->whereNull('parent_id') ->first(); - if(isset($root) && $root->rencana_biaya > 0){ - $activities = Activity::where("proyek_id", $this->proyek_id)->where("version_gantt_id", $this->version_gantt_id)->get(); + if(isset($root) && doubleval($root->rencana_biaya) > 0){ + $activities = Activity::where([['proyek_id', $this->proyek_id],['version_gantt_id', $this->version_gantt_id]])->get(); foreach ($activities as $activity) { if($isDelete && $activity->id == $this->id) continue; - $activity->bobot_planning = ( (int)$activity->rencana_biaya / $root->rencana_biaya) * 100; + $activity->bobot_planning = ( doubleval($activity->rencana_biaya) / doubleval($root->rencana_biaya)) * 100; $activity->updated_by = auth()->user() ? auth()->user()->name : "system"; $activity->saveQuietly(); From 485b9466af78bb5ec2532d6c62781cd5d4514310 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 6 Mar 2024 16:46:29 +0700 Subject: [PATCH 115/155] update type data and boot function --- app/Models/AssignMaterial.php | 37 +++++++++++++++++------------------ 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/app/Models/AssignMaterial.php b/app/Models/AssignMaterial.php index 09620ee..34fb24d 100644 --- a/app/Models/AssignMaterial.php +++ b/app/Models/AssignMaterial.php @@ -3,10 +3,8 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; -use App\Models\RequestMaterial; -use App\Models\Activity; -use App\Models\ReportActivityMaterial; - +use App\Models\{Activity,RequestMaterial,ReportActivityMaterial}; +use Illuminate\Support\Facades\DB; class AssignMaterial extends Model { protected $table = 'assign_material_to_activity'; @@ -23,24 +21,25 @@ class AssignMaterial extends Model protected $casts = [ 'id' => 'integer', 'budget' => 'string', + 'qty_planning' => 'float' ]; 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 += floatval($material->price) * floatval($data->qty_planning); - $activity->save(); - }); - - static::deleted(function($data) { - $reportActivities = ReportActivityMaterial::where('assign_material_id', $data->id)->delete(); - $activity = Activity::where('id', $data->activity_id)->first(); - $activity->rencana_biaya -= floatval($data->budget) * floatval($data->qty_planning); - $activity->save(); - }); - + DB::transaction(function () { + static::created(function($data) { + $activity = Activity::find((int)$data->activity_id); + $material = RequestMaterial::find((int)$data->material_id); + $activity->rencana_biaya += (doubleval($material->price) * doubleval($data->qty_planning)); + $activity->save(); + }); + + static::deleted(function($data) { + ReportActivityMaterial::where('assign_material_id', $data->id)->delete(); + $activity = Activity::find($data->activity_id); + $activity->rencana_biaya -= (doubleval($data->budget) * doubleval($data->qty_planning)); + $activity->save(); + }); + }, 5); } } From 074bf105a1042473381a30d70f6e296cb04c2794 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 6 Mar 2024 16:52:00 +0700 Subject: [PATCH 116/155] update type data and boot function --- app/Models/UserToActivity.php | 57 ++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/app/Models/UserToActivity.php b/app/Models/UserToActivity.php index 1b795b1..c460df2 100644 --- a/app/Models/UserToActivity.php +++ b/app/Models/UserToActivity.php @@ -4,6 +4,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\Activity; +use Illuminate\Support\Facades\DB; class UserToActivity extends Model { @@ -29,35 +30,37 @@ class UserToActivity extends Model 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(); + DB::transaction(function(){ + static::created(function($data) { + $activity = Activity::find($data->activity_id); + $getWorkingHours = UserToProyek::where([['user_id', $data->user_id],['proyek_id', $activity->proyek_id]])->first(); + $salary = 0; + if($getWorkingHours->uom_standart_rate == "Hour") { + $salary = (doubleval($getWorkingHours->standart_rate) * 8) * (int)$activity->duration * ($getWorkingHours->max_used / 100); + } else { + $salary = (doubleval($getWorkingHours->standart_rate) * (int)$activity->duration) * ($getWorkingHours->max_used / 100); + } + $activity->rencana_biaya += doubleval($salary); + $activity->save(); + }); - $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; - if ($activity->rencana_biaya < 0) { - $activity->rencana_biaya = 0; - } - $activity->save(); - }); + static::deleted(function($data) { + $activity = Activity::find($data->activity_id); + $getWorkingHours = UserToProyek::where([['user_id', $data->user_id],['proyek_id', $activity->proyek_id]])->first(); + $salary = 0; + if($getWorkingHours->uom_standart_rate == "Hour"){ + $salary = (doubleval($getWorkingHours->standart_rate) * 8) * (int)$activity->duration * ($getWorkingHours->max_used / 100); + } else { + $salary = (doubleval($getWorkingHours->standart_rate) * (int)$activity->duration) * ($getWorkingHours->max_used / 100); + } + $activity->rencana_biaya -= doubleval($salary); + if ($activity->rencana_biaya < 0) { + $activity->rencana_biaya = 0; + } + $activity->save(); + }); + }, 5); } } From 3e9ec7976a661e4dbf53e16d58716f32d5a34bd8 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 6 Mar 2024 16:52:25 +0700 Subject: [PATCH 117/155] add route --- routes/web.php | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/routes/web.php b/routes/web.php index ed2e751..146a9a7 100644 --- a/routes/web.php +++ b/routes/web.php @@ -141,16 +141,6 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/human-resource/check-old-password/{id}', 'HumanResourceController@checkOldPassword'); $router->get('/human-resource/sync', 'HumanResourceController@sync'); - $router->post('/refferal-code/search', 'RefferalCodeController@search'); - $router->post('/refferal-code/add', 'RefferalCodeController@add'); - $router->get('/refferal-code/edit/{id}', 'RefferalCodeController@edit'); - $router->put('/refferal-code/update/{id}', 'RefferalCodeController@update'); - - $router->post('/product-transaction/search', 'ProductTransactionController@search'); - $router->post('/product-transaction/add', 'ProductTransactionController@add'); - $router->get('/product-transaction/edit/{id}', 'ProductTransactionController@edit'); - $router->put('/product-transaction/update/{id}', 'ProductTransactionController@update'); - $router->post('/project-role/search', 'ProjectRoleController@search'); $router->post('/project-role/add', 'ProjectRoleController@add'); $router->get('/project-role/edit/{id}', 'ProjectRoleController@edit'); @@ -599,7 +589,15 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->delete('/demo-management/delete/{id}', 'DemoController@delete'); $router->get('/demo-management/list', 'DemoController@list'); - $router->get('information-storage/{company_name}', 'Controller@storage'); + $router->get('/information-storage/{company_name}', 'Controller@storage'); + + $router->post('/register-user','UserRegisterController@add'); + + $router->post('/refferal-code/search', 'RefferalCodeController@search'); + $router->post('/refferal-code/add', 'RefferalCodeController@add'); + $router->get('/refferal-code/edit/{id}', 'RefferalCodeController@edit'); + $router->put('/refferal-code/update/{id}', 'RefferalCodeController@update'); + $router->post('/product-transaction/edit/{id}', 'ProductTransactionController@add'); $router->put('/product-transaction/update/{id}', 'ProductTransactionController@update'); $router->post('/product-transaction/search', 'ProductTransactionController@search'); From 8757245fc0dc9b0824f8d218682459b4c70f418f Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 12 Mar 2024 15:14:36 +0700 Subject: [PATCH 118/155] handle super admin --- app/Http/Controllers/AuthController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 0730cbf..9995ba4 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -45,8 +45,8 @@ class AuthController extends Controller if ($usernameCheck & $passwordCheck) { $user = User::where([['username', $username],['password', md5($password)]])->first(); $checkExpiredOspro = $this->setExpiredTimeOspro($user['company_id']); - if($checkExpiredOspro === false) { - return response()->json(['status' => 'error', 'message' => 'Expired! Please update license!'], 201); + if($checkExpiredOspro === false && $user['company_id'] != null) { + return response()->json(['status' => 'error', 'message' => 'Expired! Please update license!','$checkExpiredOspro'=>$checkExpiredOspro], 201); } if ($is_mobile) { $fcm_token = $request->fcm_token; From 5792ebc2453cfd249b5fc2c095a779f22a30c502 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 12 Mar 2024 15:14:36 +0700 Subject: [PATCH 119/155] handle super admin --- app/Http/Controllers/AuthController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 0730cbf..fbb2e3b 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -45,7 +45,7 @@ class AuthController extends Controller if ($usernameCheck & $passwordCheck) { $user = User::where([['username', $username],['password', md5($password)]])->first(); $checkExpiredOspro = $this->setExpiredTimeOspro($user['company_id']); - if($checkExpiredOspro === false) { + if($checkExpiredOspro === false && $user['company_id'] != null) { return response()->json(['status' => 'error', 'message' => 'Expired! Please update license!'], 201); } if ($is_mobile) { From 1f3eb8576a5273a715d98352c4a1b7b5183c3e70 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Thu, 14 Mar 2024 15:39:23 +0700 Subject: [PATCH 120/155] update delete relative company --- app/Http/Controllers/CompanyController.php | 39 ++++++++++++++-------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 3a0cecb..b828469 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -2,9 +2,9 @@ namespace App\Http\Controllers; -use App\Models\Company; -use App\Models\MenuCompany; +use App\Models\{User, RoleMenu, Role, ProductTransaction, MenuCompany, Company}; use Illuminate\Http\Request; +use Illuminate\Support\Facades\DB; class CompanyController extends Controller { @@ -66,8 +66,6 @@ class CompanyController extends Controller return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); die(); } - - if ($result) { return response()->json(['status' => 'success', 'message' => 'data Company successfully updated!', 'code' => 200], 200); } else { @@ -77,24 +75,37 @@ class CompanyController extends Controller public function delete($id) { - $data = Company::find($id); - + DB::beginTransaction(); + $data = Company::find((int)$id); if ($data) { - MenuCompany::where('company_id',$id)->delete(); - $delete = $data->delete(); + $this->deleteRelative((int)$data['id']); + if ($data->delete()) { + DB::commit(); + return response()->json(['status' => 'success', 'message' => 'Data Company successfully deleted!', 'code' => 200], 200); + } else { + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Data Company failed deleted!', 'code' => 400], 400); + } } else { - return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Data Company not found!', 'code' => 400], 400); die(); } + } - - if ($delete) { - return response()->json(['status' => 'success', 'message' => 'data Company successfully deleted!', 'code' => 200], 200); - } else { - return response()->json(['status' => 'failed', 'message' => 'data Company failed deleted!', 'code' => 400], 400); + private function deleteRelative($company_id) + { + MenuCompany::where('company_id', $company_id)->delete(); + User::where('company_id', $company_id)->delete(); + $role = Role::where('company_id', $company_id)->first(); + if ($role) { + RoleMenu::where('role_id', $role->id)->delete(); + $role->delete(); } + ProductTransaction::where('company_id', $company_id)->delete(); } + public function search(Request $request) { $payload = $request->all(); From 921bfad15d7c7eb4fe82bc67a7c12c886352840b Mon Sep 17 00:00:00 2001 From: wahyuun Date: Thu, 14 Mar 2024 15:39:57 +0700 Subject: [PATCH 121/155] update register --- .../Controllers/UserRegisterController.php | 177 +++++++++++++----- 1 file changed, 125 insertions(+), 52 deletions(-) diff --git a/app/Http/Controllers/UserRegisterController.php b/app/Http/Controllers/UserRegisterController.php index 009a729..1a31eaf 100644 --- a/app/Http/Controllers/UserRegisterController.php +++ b/app/Http/Controllers/UserRegisterController.php @@ -5,38 +5,49 @@ namespace App\Http\Controllers; use Carbon\Carbon; use Illuminate\Support\Str; use Illuminate\Http\Request; -use Illuminate\Support\Facades\{DB,Validator}; -use App\Models\{Company, HumanResource, Menu, ProductTransaction, RefferalCode, Role, RoleMenu, MenuCompany}; +use Illuminate\Support\Facades\{DB,Log}; +use App\Models\{User, Company, HumanResource, Menu, ProductTransaction, RefferalCode, Role, RoleMenu, MenuCompany}; +const URL_EMAIL = 'https://notifapp.odm-iu.com/service-mail/notif_mail.php'; class UserRegisterController extends Controller { public function add(Request $request) { - DB::transaction(function () use ($request) { - $validator = Validator::make($request->all(), [ - 'refferal' => 'unique:refferal_code,code', - 'cluster' => 'required|string', - 'address' => 'required|string', - 'email' => 'required|unique:' . ($request->type_account === 'Company' ? 'm_company' : 'm_users') . ',email', - 'type_paket' => 'required|in:Basic, Free', - 'phone_no' => 'required', - 'type_account' => 'string|in:Personal, Company', - 'company_name' => 'required|string', - 'username' => 'string|required|unique:' . ($request->type_account === 'Personal' ? 'm_users' : '') . ',username' - ]); - if ($validator->fails()) { - return response()->json(['status' => 'failed', 'message' => $validator->errors()->first(), 'code' => 400], 400); - } - $data = $validator->validated(); + DB::beginTransaction(); + $this->validate($request, [ + 'cluster' => 'required|string', + 'address' => 'required|string', + 'email' => 'required|string', + 'type_paket' => ($request->type_account === 'Personal' ? 'required' : 'nullable') . '|in:Basic,Free', + 'phone_no' => 'required', + 'type_account' => 'string|in:Personal,Company', + 'company_name' => 'required|string', + 'username' => 'required|string' + ]); + try { + $data = $request->all(); + $company_name = $data['company_name']; $type_account = $data['type_account']; - $refferal = $data['refferal']; + $refferal = $request->refferal ? $data['refferal'] : null; $cluster = $data['cluster']; $address = $data['address']; $phone_no = $data['phone_no']; $email = $data['email']; $username = $data['username']; - $type_paket = $data['type_paket']; + $type_paket = $request->type_account === 'Personal' ? $data['type_paket'] : ''; + $company_address = $request->type_account === 'Company' ? $data['companyAddress'] : ''; + $full_name = $request->type_account === 'Personal' ? $data['full_name'] : ''; + + // check email & username already exist + $emailExists = Company::where('email', $email)->exists() || User::where('email', $email)->exists(); + if ($emailExists) { + return response()->json(['status' => 'failed', 'message' => 'Email already exists, please check again!', 'code' => 500], 500); + } + $usernameExists = User::where('username', $username)->exists(); + if ($usernameExists) { + return response()->json(['status' => 'failed', 'message' => 'Username already exists, please check again!', 'code' => 500], 500); + } // Get last registration number $getCompany = $this->getCompany(); @@ -50,7 +61,9 @@ class UserRegisterController extends Controller 'address' => $address, 'type_account' => $type_account, 'username' => $username, - 'type_paket' => $type_paket + 'type_paket' => $type_paket, + 'companyAddress' => $company_address, + 'full_name' => $full_name ); if(empty($refferal)) { @@ -58,47 +71,48 @@ class UserRegisterController extends Controller } else { $getRefferal = $this->getRefferalCode($refferal); if(empty($getRefferal)) { - return response()->json(['status' => 'failed', 'message' => 'Refferal Code Not Found!', 'code' => 404], 404); + return response()->json(['status' => 'failed', 'message' => 'Refferal code not found!', 'code' => 404], 404); } - $addCompany = $this->addCompany($formDataCompany, $getRefferal['id']); + $addCompany = $this->addCompany($formDataCompany, (int)$getRefferal['id']); } if(empty($addCompany)) { return; - die(); } $addRole = $this->addRole((int)$addCompany['id']); if(empty($addRole)) { return; - die(); } $addHR = $this->addHR((int)$addCompany['id'], (int)$addRole['id'], $formDataCompany); if(empty($addHR)) { return; - die(); } $getMenu = $this->getMenu(); if(empty($getMenu)) { return; - die(); } - $this->addTransaction((int)$addCompany['id'], $formDataCompany); + if($request->type_account === 'Personal') { + $this->addTransaction((int)$addCompany['id'], $formDataCompany); + } $addMenuCompany = $this->addMenuCompany($getMenu, (int)$addCompany['id']); if(empty($addMenuCompany)) { return; - die(); } $addMenuRole = $this->addMenuRole($getMenu, (int)$addRole['id']); - - if($addMenuRole) { - return response()->json(['status' => 'success', 'message' => 'Register is successfully!', 'code' => 200], 200); + if(empty($addMenuRole)) { + return; } - - },3); + DB::commit(); + return response()->json(['status' => 'success', 'message' => 'Register is successful, please check your email!', 'generateRandom' => $addHR['generateRandom'], 'code' => 200], 200); + } catch (\Throwable $th) { + DB::rollBack(); + Log::channel('daily')->error($th->getMessage()); + return response()->json(['status' => 'failed', 'message' => 'Failed to register, please check again!', 'code' => 500], 500); + } } protected function getRefferalCode($refferal) @@ -119,11 +133,11 @@ class UserRegisterController extends Controller 'date_register' => Carbon::now(), 'template_id' => 1, 'email' => $formData['email'], - 'address' => $formData['address'], + 'address' => $formData['type_account'] === 'Company' ? $formData['companyAddress'] : $formData['address'], 'phone_no' => $formData['phone_no'], 'type_account' => $formData['type_account'], 'is_active' => true, - 'discount_id' => $id_refferal === null ? null : (int)$id_refferal + 'discount_id' => $id_refferal === null ? null : $id_refferal ); $result = Company::create($formData); return $result; @@ -142,25 +156,27 @@ class UserRegisterController extends Controller protected function addHR($id_company, $id_role, $data) { - $generatePassword = Str::password(10); + $generateRandom = Str::random(8); $formData = array( - 'name'=> $data['company_name'], + 'name'=> $data['type_account'] === 'Company' ? $data['username'] : $data['full_name'], 'phone_number'=> $data['phone_no'], 'email'=> $data['email'], 'username' => $data['username'], - 'password'=> $generatePassword, - 'role_id'=> (int)$id_role, - 'ktp_number'=> $data['type_account'] === 'Company' ? 'CP-' : 'PR-' . Str::random(5), - 'employee_type'=>'employee', + 'password'=> md5($generateRandom), + 'role_id'=> $id_role, + 'ktp_number'=> $data['type_account'] === 'Company' ? 'CP-'. $generateRandom : 'PR-' . $generateRandom, + 'employee_type'=> 'employee', 'address' => $data['address'], 'status_resource'=> 'active', - 'company_id'=> (int)$id_company + 'company_id'=> $id_company ); $result = HumanResource::create($formData); - + if(!empty($result)) { + $this->sendEmail($data['email'], $generateRandom); + } return [ 'result' => $result, - 'generatePassword' => $generatePassword + 'generateRandom' => $generateRandom ]; } @@ -170,7 +186,7 @@ class UserRegisterController extends Controller if($data->exists()){ $data->delete(); } - if (is_array($baseDataMenu) && count($baseDataMenu) > 0 && isset($baseDataMenu)) { + if (is_object($baseDataMenu) && count($baseDataMenu) > 0 && isset($baseDataMenu)) { $countRes = 0; foreach ($baseDataMenu as $menu) { $dataInsert = array( @@ -193,16 +209,16 @@ class UserRegisterController extends Controller if ($countRes > 0) { return $result; } else { - return $result; + die(); } } else { - return false; + die(); } } protected function addMenuRole($baseDataMenu, $id_role) { - if (is_array($baseDataMenu) && count($baseDataMenu) > 0 && isset($baseDataMenu)) { + if (is_object($baseDataMenu) && count($baseDataMenu) > 0 && isset($baseDataMenu)) { $countRes = 0; foreach ($baseDataMenu as $menu) { $dataInsert = array( @@ -219,10 +235,10 @@ class UserRegisterController extends Controller if ($countRes > 0) { return $result; } else { - return $result; + die(); } } else { - return false; + die(); } } @@ -263,11 +279,68 @@ class UserRegisterController extends Controller $lastRegistrationNumber = $company['registration_no']; $lastNumber = (int)preg_replace('/\D/', '', $lastRegistrationNumber); $newNumber = $lastNumber + 1; - // $newRegistrationNumber = Str::beforeLast($lastRegistrationNumber, $lastNumber) . $newNumber; $newRegistrationNumber = 'RG-'. $newNumber; + } else{ + return false; } return [ 'newRegistrationNumber' => $newRegistrationNumber ]; } + + public function sendEmail($email, $password) + { + $user = User::select('email', 'name', 'username')->where('email', $email)->first(); + if (!$user) { + return response()->json(['status' => 'error', 'message' => 'e-mail not found '], 400); + } else { + $this->reqHttpCurl($email, $password, $user->username, $user->name); + return response()->json(['status' => 'error', 'code'=>400, 'message' => 'e-mail not found '], 400); + } + } + + private function reqHttpCurl($email, $password, $username, $name) + { + $postData = [ + "to" => $email, + "name" => $name, + "username" => $username, + "password" => $password, + "from" => "app.integrasia@integrasiautama.com", + "alias_from" => "OSPRO", + "subject" => "Registration OSPRO", + "body" => "registration-ospro" + ]; + + $curl = curl_init(); + + curl_setopt_array($curl, array( + CURLOPT_URL => URL_EMAIL, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30000, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode($postData), + CURLOPT_HTTPHEADER => array( + // Set here requred headers + "accept: */*", + "accept-language: en-US,en;q=0.8", + "content-type: application/json", + ), + )); + + $response = curl_exec($curl); + $err = curl_error($curl); + + curl_close($curl); + + if ($err) { + echo "cURL Error #:" . $err; + } else { + print_r(json_decode($response)); + } + + } } From 6cf4b3aab3118ebc78ce634c736c8489d08fa87f Mon Sep 17 00:00:00 2001 From: wahyuun Date: Thu, 14 Mar 2024 15:40:16 +0700 Subject: [PATCH 122/155] add DB transaction --- app/Http/Controllers/ProjectController.php | 1041 ++++++++++---------- 1 file changed, 530 insertions(+), 511 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 0f4e54b..bbad373 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -3,46 +3,16 @@ namespace App\Http\Controllers; use DateTime; -use App\Models\Link; -use App\Models\User; -use App\Models\Image; -use App\Models\Company; -use App\Models\Holiday; -use App\Models\Project; -use App\Models\Activity; -use App\Models\ReportK3; use App\Jobs\ProcessSCurve; -use App\Models\AssignTools; -use App\Models\OfficeHours; -use App\Models\ProjectType; -use App\Models\ProjectPhase; -use App\Models\ProjectRisks; -use App\Models\UserToProyek; -use App\Models\VersionGantt; use Illuminate\Http\Request; -use App\Models\HierarchyFtth; -use App\Models\ProjectIssues; -use App\Models\AssignMaterial; -use App\Models\DokumenProject; -use App\Models\ProjectCharter; -use App\Models\ReportActivity; -use App\Models\ShowHideColumn; -use App\Models\UserToActivity; -use App\Models\ActivityDokumen; -use App\Models\CommentActivity; -use App\Models\ProjectApproval; -use App\Models\RequestMaterial; -use App\Models\ProjectMileStone; -use App\Models\ProjectChecklists; -use App\Models\ProductTransaction; -use Illuminate\Support\Facades\DB; -use App\Models\ProjectParticipants; -use App\Models\FolderDocumentProyek; -use App\Models\ProjectToChecklistK3; -use App\Helpers\MasterFunctionsHelper; -use App\Models\ReportActivityMaterial; +use App\Models\{ReportActivityMaterial,ProjectToChecklistK3,FolderDocumentProyek,ProjectParticipants,ProductTransaction,ProjectChecklists, + ProjectMileStone,RequestMaterial,ProjectApproval,CommentActivity,ActivityDokumen,UserToActivity,ShowHideColumn,ReportActivity,ProjectCharter,DokumenProject, + AssignMaterial,ProjectIssues,HierarchyFtth,VersionGantt,UserToProyek,ProjectRisks,ProjectPhase,ProjectType,OfficeHours,AssignTools,ReportK3,Activity,Project, + Holiday,Company,Image,User,Link +}; use Illuminate\Database\Query\Builder; -use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\{Artisan,DB}; +use App\Helpers\MasterFunctionsHelper; const API_GEOLOCATION = "https://nominatim.oslogdev.com/search/ADDR?format=json&addressdetails=1&limit=1"; @@ -60,56 +30,59 @@ class ProjectController extends Controller 'type_proyek_id' => 'required', 'company_id' => 'required' ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - $data['created_by_id'] = $this->currentId; - - if (empty($data['phase_id'])) { - $data['phase_id'] = 1; - } - - $transaction = ProductTransaction::query() - ->where('company_id', $request->company_id); - $cloneQueryTransaction = clone $transaction; - - $countCreate = false; - $projectResult = Project::query() - ->selectRaw('count(*) as total_project') - ->where('company_id', $request->company_id) - ->first(); - if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { - if($projectResult['total_project'] < 10) { - $countCreate = true; + DB::beginTransaction(); + try { + $data = $request->all(); + $data['created_by'] = $this->currentName; + $data['created_by_id'] = $this->currentId; + + if (empty($data['phase_id'])) { + $data['phase_id'] = 1; } - } elseif ($cloneQueryTransaction->where([['type_paket','Free'],['amount',0]])->exists()) { - if($projectResult['total_project'] < 1) { + $transaction = ProductTransaction::query() + ->where('company_id', $request->company_id); + $cloneQueryTransaction = clone $transaction; + + $countCreate = false; + $projectResult = Project::query() + ->selectRaw('count(*) as total_project') + ->where('company_id', $request->company_id) + ->first(); + if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { + if($projectResult['total_project'] < 10) { + $countCreate = true; + } + } elseif ($cloneQueryTransaction->where([['type_paket','Free'],['amount',0]])->exists()) { + if($projectResult['total_project'] < 1) { + $countCreate = true; + } + } else { $countCreate = true; } - } else { - $countCreate = true; - } - if($countCreate) { - $result = Project::create($data); - } else { - return response()->json(['status' => 'failed', 'message' => 'Limited to create project!', 'code' => 500], 500); + if($countCreate) { + $result = Project::create($data); + if (!$result) { + return response()->json(['status' => 'failed', 'message' => 'Failed to add data!', 'code' => 500], 500); + } else { + $this->createOfficeHours($result['id']); + $dataResultInsert = Project::where([['nama', $data['nama']],['mulai_proyek', $data['mulai_proyek']]])->first(); + DB::commit(); + return response()->json(['status' => 'success', 'message' => 'Data added!', 'data_result' => $dataResultInsert, 'code' => 200], 200); + } + } else { + return response()->json(['status' => 'failed', 'message' => 'Limited to create project!', 'code' => 500], 500); + } + } catch (\Throwable $th) { + DB::rollBack(); } - - 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)) + if (empty($id) || !is_int((int)$id)) { return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + } // $result = Project::query() // ->from('m_proyek AS mp') @@ -157,28 +130,30 @@ class ProjectController extends Controller ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') ->where('m_proyek.id', $id) ->first(); - if (!$result) - return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - - return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + if (!$result) { + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + } else { + 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); + 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); + if ($data) { + if ($data->update($request->all())) { + return response()->json(['status' => 'success', 'message' => 'Data updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Failed to update!', 'code' => 500], 500); + } + } else { + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + } } private function createOfficeHours($proyek_id) @@ -209,101 +184,109 @@ class ProjectController extends Controller public function delete($id, $company_id) { + DB::beginTransaction(); $data = Project::find($id); - - if (!$data) + if ($data) { + $this->deleteRelative($id, $company_id); + if ($data->delete()) { + DB::commit(); + return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); + } else { + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Delete failed!', 'code' => 500], 500); + } + } else { + DB::rollBack(); return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - - $this->deleteRelative($id, $company_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, $company_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(); - ProjectChecklists::where('proyek_id', $project_id)->delete(); - ProjectIssues::where('proyek_id', $project_id)->delete(); - ProjectRisks::where('proyek_id', $project_id)->delete(); - ProjectToChecklistK3::where('proyek_id', $project_id)->delete(); - HierarchyFtth::where('project_id', $project_id)->delete(); - AssignTools::where('proyek_id', $project_id)->delete(); - OfficeHours::where('proyek_id', $project_id)->delete(); - ReportK3::where('proyek_id', $project_id)->delete(); - RequestMaterial::where('proyek_id', $project_id)->delete(); - $this->deleteVersionGantt($project_id, $company_id); - $this->deleteDokumenProject($project_id, $company_id); + DB::transaction(function() use($project_id, $company_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(); + ProjectChecklists::where('proyek_id', $project_id)->delete(); + ProjectIssues::where('proyek_id', $project_id)->delete(); + ProjectRisks::where('proyek_id', $project_id)->delete(); + ProjectToChecklistK3::where('proyek_id', $project_id)->delete(); + HierarchyFtth::where('project_id', $project_id)->delete(); + AssignTools::where('proyek_id', $project_id)->delete(); + OfficeHours::where('proyek_id', $project_id)->delete(); + ReportK3::where('proyek_id', $project_id)->delete(); + RequestMaterial::where('proyek_id', $project_id)->delete(); + $this->deleteVersionGantt($project_id, $company_id); + $this->deleteDokumenProject($project_id, $company_id); + },5); } private function deleteVersionGantt($project_id, $company_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(); - $company = Company::find($company_id); - if($company) { - $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); - foreach ($dataRa as $ra) { - $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); - foreach ($images as $image) { - if (file_exists($destinationPath['pathImage'] . $image->image)) { - unlink($destinationPath['pathImage'] . $image->image); + DB::transaction(function() use($project_id, $company_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(); + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + foreach ($dataRa as $ra) { + $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); + foreach ($images as $image) { + if (file_exists($destinationPath['pathImage'] . $image->image)) { + unlink($destinationPath['pathImage'] . $image->image); + } } + Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); } - 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($destinationPath['pathActivityDocument'] . $ad->file)) { - unlink($destinationPath['pathActivityDocument'] . $ad->file); + $dataAd = ActivityDokumen::whereIn("activity_id", $activityIds)->get(); + foreach ($dataAd as $ad) { + if (file_exists($destinationPath['pathActivityDocument'] . $ad->file)) { + unlink($destinationPath['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(); + 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(); + },5); } private function deleteDokumenProject($project_id, $company_id) { - $dataDokumen = DokumenProject::where("type_dokumen", "project-document-out-folder")->where('ref_id', $project_id)->get(); - $company = Company::find($company_id); - if($company) { - $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + DB::transaction(function() use($project_id, $company_id){ + $dataDokumen = DokumenProject::where([['type_dokumen', 'project-document-out-folder'],['ref_id', $project_id]])->get(); + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + foreach ($dataDokumen as $dokumen) { + if (file_exists($destinationPath['pathDocument'] . $dokumen->file)) { + unlink($destinationPath['pathDocument'] . $dokumen->file); + } + } + } + DokumenProject::where([['type_dokumen', 'project-document-out-folder'],['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($destinationPath['pathDocument'] . $dokumen->file)) { unlink($destinationPath['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($destinationPath['pathDocument'] . $dokumen->file)) { - unlink($destinationPath['pathDocument'] . $dokumen->file); - } - } - - DokumenProject::where("type_dokumen", "project-document-in-folder")->whereIn('ref_id', $ref_ids)->delete(); + DokumenProject::where("type_dokumen", "project-document-in-folder")->whereIn('ref_id', $ref_ids)->delete(); + },5); } public function search(Request $request) @@ -313,7 +296,6 @@ class ProjectController extends Controller $dataBuilder = $this->setUpPayload($payload, 'm_proyek'); $builder = $dataBuilder['builder']; $countBuilder = $dataBuilder['count']; - // $builder->where("selfTable.created_by",$this->currentName); $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); @@ -322,94 +304,90 @@ class ProjectController extends Controller public function list() { - $data = Project::select( - 'id', - 'kode_sortname', - 'jumlah_stakeholder', - 'nama', - 'mulai_proyek', - 'akhir_proyek', - 'area_kerja', - 'lokasi_kantor', - 'rencana_biaya', - 'biaya_actual', - 'company', - 'pm_id', - 'type_proyek_id', - 'divisi_id', - 'persentase_progress', - 'keterangan', - 'durasi_proyek', - 'progress_by_worklog', - 'status', - 'currency_symbol', - 'currency_code', - 'currency_name', - 'project_objectives', - 'considered_success_when', - 'potential_risk', - 'testing_environment', - 'currency_code', - 'currency_symbol', - 'currency_name', - 'budget_health', - 'phase_id', - 'calculation_status', - 'created_at', - 'created_by', - 'updated_at', - 'updated_by' - )->orderBy('id', 'desc') - // ->where("created_by",$this->currentName) - ->get(); - $countData = $data->count(); - - if (!$data) - return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - - $totalPlannedCost = array_sum(array_map('intval', array_column($data->toArray(), 'plannedCost'))); - $totalActualCost = $data->sum('actualCost'); - $manpowers = User::count(); - $projectsOnDanger = Project::where('budget_health', 'overrun')->count(); - $projectPhases = ProjectPhase::orderBy('order', 'asc')->pluck('name'); - $projectTypes = ProjectType::orderBy('id', 'asc')->pluck('name'); - try { - $projectsByPhase = DB::table('m_proyek') - ->select('m_proyek_phase.name', 'm_proyek_phase.color', DB::raw('count(*) as total')) - ->join('m_proyek_phase', 'm_proyek_phase.id', '=', 'm_proyek.phase_id') - ->groupBy('m_proyek_phase.name', 'm_proyek_phase.color') - ->get(); - } catch (\Exception $e) { - return response()->json(['message' => $e->getMessage()]); - } - try { - $projectsByType = DB::table('m_proyek') - ->select('m_type_proyek.name', DB::raw('count(m_type_proyek.id) as total')) - ->join('m_type_proyek', 'm_type_proyek.id', '=', 'm_proyek.type_proyek_id') - ->groupBy('m_type_proyek.name') - ->get(); - } catch (\Exception $e) { - return response()->json(['message' => $e->getMessage()]); - } + DB::beginTransaction(); + try { + $data = Project::select( + 'id', + 'kode_sortname', + 'jumlah_stakeholder', + 'nama', + 'mulai_proyek', + 'akhir_proyek', + 'area_kerja', + 'lokasi_kantor', + 'rencana_biaya', + 'biaya_actual', + 'company', + 'pm_id', + 'type_proyek_id', + 'divisi_id', + 'persentase_progress', + 'keterangan', + 'durasi_proyek', + 'progress_by_worklog', + 'status', + 'currency_symbol', + 'currency_code', + 'currency_name', + 'project_objectives', + 'considered_success_when', + 'potential_risk', + 'testing_environment', + 'currency_code', + 'currency_symbol', + 'currency_name', + 'budget_health', + 'phase_id', + 'calculation_status', + 'created_at', + 'created_by', + 'updated_at', + 'updated_by' + )->orderByDesc('id') + ->get(); + $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, - 'totalPlannedCost' => $totalPlannedCost, - 'totalActualCost' => $totalActualCost, - 'totalRevenue' => $totalPlannedCost - $totalActualCost, - 'manpowers' => $manpowers, - 'projectsOnDanger' => $projectsOnDanger, - 'projectPhases' => $projectPhases, - 'projectsByPhase' => $projectsByPhase, - 'projectTypes' => $projectTypes, - 'projectsByType' => $projectsByType, - ], - 200 - ); + $totalPlannedCost = array_sum(array_map('intval', array_column($data->toArray(), 'plannedCost'))); + $totalActualCost = $data->sum('actualCost'); + $manpowers = User::count(); + $projectsOnDanger = Project::where('budget_health', 'overrun')->count(); + $projectPhases = ProjectPhase::orderBy('order', 'asc')->pluck('name'); + $projectTypes = ProjectType::orderBy('id', 'asc')->pluck('name'); + $projectsByPhase = DB::table('m_proyek') + ->select('m_proyek_phase.name', 'm_proyek_phase.color', DB::raw('count(*) as total')) + ->join('m_proyek_phase', 'm_proyek_phase.id', '=', 'm_proyek.phase_id') + ->groupBy('m_proyek_phase.name', 'm_proyek_phase.color') + ->get(); + $projectsByType = DB::table('m_proyek') + ->select('m_type_proyek.name', DB::raw('count(m_type_proyek.id) as total')) + ->join('m_type_proyek', 'm_type_proyek.id', '=', 'm_proyek.type_proyek_id') + ->groupBy('m_type_proyek.name') + ->get(); + DB::commit(); + return response()->json( + [ + 'status' => 'success', + 'code' => 200, + 'data' => $data, + 'totalRecord' => $countData, + 'totalPlannedCost' => $totalPlannedCost, + 'totalActualCost' => $totalActualCost, + 'totalRevenue' => $totalPlannedCost - $totalActualCost, + 'manpowers' => $manpowers, + 'projectsOnDanger' => $projectsOnDanger, + 'projectPhases' => $projectPhases, + 'projectsByPhase' => $projectsByPhase, + 'projectTypes' => $projectTypes, + 'projectsByType' => $projectsByType, + ], + 200 + ); + } catch (\Throwable $th) { + DB::rollBack(); + } } public function getListProjectTask($id) @@ -420,10 +398,12 @@ class ProjectController extends Controller ->groupBy("m_proyek.proyek_id") ->get(); - if (!$data) - return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + if ($data) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + } - return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } public function getSCurve(Request $request) @@ -469,83 +449,93 @@ class ProjectController extends Controller public static function setSyncDate($activity_id, $activity, $report) { - $status = AssignMaterial::where('activity_id', $activity_id)->first(); - if (!isset($status)) { - $reports = array( - 'activity_id' => $activity_id, - 'min_date' => new DateTime($activity->start_date), - 'max_date' => new DateTime($activity->end_date), - 'status' => 'open' - ); - return $reports; - } - if (!isset($status->status_activity)) { - $status->status_activity = 'open'; - } - if ($status->status_activity != 'done') { - $minDate = date_create($report->report_date); - $maxDate = date_create($report->report_date); - date_add($maxDate, date_interval_create_from_date_string($activity->duration . " days")); - } else { - $material = AssignMaterial::where('activity_id', $activity_id)->first(); - $minDate = date_create($material->start_activity); - $maxDate = date_create($material->finish_activity); - } - $reports = array( - 'activity_id' => $activity_id, - 'min_date' => $minDate, - 'max_date' => $maxDate, - 'status' => $status->status_activity - ); - return $reports; + DB::beginTransaction(); + try { + $status = AssignMaterial::where('activity_id', $activity_id)->first(); + if (!isset($status)) { + DB::commit(); + return [ + 'activity_id' => $activity_id, + 'min_date' => new DateTime($activity->start_date), + 'max_date' => new DateTime($activity->end_date), + 'status' => 'open' + ]; + } + if (!isset($status->status_activity)) { + $status->status_activity = 'open'; + } + if ($status->status_activity != 'done') { + $minDate = date_create($report->report_date); + $maxDate = date_create($report->report_date); + date_add($maxDate, date_interval_create_from_date_string($activity->duration . " days")); + } else { + $material = AssignMaterial::where('activity_id', $activity_id)->first(); + $minDate = date_create($material->start_activity); + $maxDate = date_create($material->finish_activity); + } + DB::commit(); + return [ + 'activity_id' => $activity_id, + 'min_date' => $minDate, + 'max_date' => $maxDate, + 'status' => $status->status_activity + ]; + } catch (\Throwable $th) { + DB::rollBack(); + } } public function synchronizeReport($gantt_id) { - $activities = Activity::where("version_gantt_id", $gantt_id)->get(); - $reports = []; - - foreach ($activities as $activity) { - $activity_id = $activity->id; - $countReports = ReportActivityMaterial::where('activity_id', $activity_id)->count(); - if ($countReports === 1) { - $dataReports = ReportActivityMaterial::where('activity_id', $activity_id)->orderBy('report_date')->get(); - foreach ($dataReports as $dr) { - $reports[] = ProjectController::setSyncDate($activity_id, $activity, $dr); - } - } - if ($countReports > 1) { - $firstReport = ReportActivityMaterial::where('activity_id', $activity_id)->orderBy('report_date')->first(); - $reports[] = ProjectController::setSyncDate($activity_id, $activity, $firstReport); - } - $successor = Link::where('t_activity_id', $activity->id)->first(); - if ($successor) { - $predecessor = Activity::find($successor->s_activity_id); - $activity->start_date = $predecessor->end_date; - $end_date = new DateTime($activity->start_date); - $end_date->modify("+" . $activity->duration . " days"); - $activity->end_date = $end_date->format("Y-m-d H:i:sO"); - } - $activity->save(); - } - for ($i = 0; $i < count($reports); $i++) { - $activity = Activity::find($reports[$i]['activity_id']); - if ($reports[$i]['status'] != 'done') { - $reports[$i]['max_date']->modify('-1 day'); - } else if ($reports[$i]['status'] == 'done') { - $activity->actual_end = $reports[$i]['max_date']->setTime(23, 59, 59); - } - $activity->start_date = $reports[$i]['min_date']; //same early - $activity->end_date = $reports[$i]['max_date']->setTime(23, 59, 59); // same early - $startDate = new DateTime($activity->start_date); - $endDate = new DateTime($activity->end_date); - $duration = MasterFunctionsHelper::countDays($activity->version_gantt_id, $startDate, $endDate); - $activity->duration = $duration; - $activity->actual_start = $reports[$i]['min_date']; - $activity->save(); - } - - return response()->json(['status' => 'success', 'message' => 'Synchronize to report success!', 'code' => 200], 200); + DB::beginTransaction(); + try { + $activities = Activity::where("version_gantt_id", $gantt_id)->get(); + $reports = []; + + foreach ($activities as $activity) { + $activity_id = $activity->id; + $countReports = ReportActivityMaterial::where('activity_id', $activity_id)->count(); + if ($countReports === 1) { + $dataReports = ReportActivityMaterial::where('activity_id', $activity_id)->orderBy('report_date')->get(); + foreach ($dataReports as $dr) { + $reports[] = self::setSyncDate($activity_id, $activity, $dr); + } + } + if ($countReports > 1) { + $firstReport = ReportActivityMaterial::where('activity_id', $activity_id)->orderBy('report_date')->first(); + $reports[] = self::setSyncDate($activity_id, $activity, $firstReport); + } + $successor = Link::where('t_activity_id', $activity->id)->first(); + if ($successor) { + $predecessor = Activity::find($successor->s_activity_id); + $activity->start_date = $predecessor->end_date; + $end_date = new DateTime($activity->start_date); + $end_date->modify("+" . $activity->duration . " days"); + $activity->end_date = $end_date->format("Y-m-d H:i:sO"); + } + $activity->save(); + } + for ($i = 0; $i < count($reports); $i++) { + $activity = Activity::find($reports[$i]['activity_id']); + if ($reports[$i]['status'] != 'done') { + $reports[$i]['max_date']->modify('-1 day'); + } else if ($reports[$i]['status'] == 'done') { + $activity->actual_end = $reports[$i]['max_date']->setTime(23, 59, 59); + } + $activity->start_date = $reports[$i]['min_date']; //same early + $activity->end_date = $reports[$i]['max_date']->setTime(23, 59, 59); // same early + $startDate = new DateTime($activity->start_date); + $endDate = new DateTime($activity->end_date); + $duration = MasterFunctionsHelper::countDays($activity->version_gantt_id, $startDate, $endDate); + $activity->duration = $duration; + $activity->actual_start = $reports[$i]['min_date']; + $activity->save(); + } + DB::commit(); + return response()->json(['status' => 'success', 'message' => 'Synchronize to report success!', 'code' => 200], 200); + } catch (\Throwable $th) { + DB::rollBack(); + } } public function setBaseline($gantt_id) @@ -566,10 +556,7 @@ class ProjectController extends Controller public function setBaselineActivity($activity_id, $gantt_id) { - $activity = Activity::where([ - ["version_gantt_id", $gantt_id], - ['id',$activity_id] - ])->first(); + $activity = Activity::where([["version_gantt_id", $gantt_id],['id',$activity_id]])->first(); $activity->update([ "planned_start" => $activity->start_date, "planned_end" => $activity->end_date, @@ -581,30 +568,32 @@ class ProjectController extends Controller public function getInvoiceIntegration(Request $request) { - $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); - $search = urlencode($request->search); - if (empty($search)) - return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); - - $response = MasterFunctionsHelper::curlReq($url); - if (isset($request->gantt_id)) { - $response->data->total_cost = $response->data->total_cost / $ganttCount; - } + DB::beginTransaction(); + try { + $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); + $search = urlencode($request->search); + if (empty($search)) { + return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); + } + $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); - return response()->json(['status' => 'success', 'data' => $response, 'code' => 200], 200); + $response = MasterFunctionsHelper::curlReq($url); + if (isset($request->gantt_id)) { + $response->data->total_cost = $response->data->total_cost / $ganttCount; + } + DB::commit(); + return response()->json(['status' => 'success', 'data' => $response, 'code' => 200], 200); + } catch (\Throwable $th) { + DB::rollBack(); + } } public function getByUser($id) { - $alias = "utp"; $userProyek = UserToProyek::query() - ->from('assign_hr_to_proyek AS ' . $alias) - ->where([ - ['is_customer', true], - ['user_id', $id] - ]) - ->leftJoin('m_users', $alias . '.user_id', '=', 'm_users.id') - ->leftJoin('m_proyek', $alias . '.proyek_id', '=', 'm_proyek.id') + ->from('assign_hr_to_proyek AS utp') + ->where([['is_customer', true],['user_id', $id]]) + ->leftJoin('m_users', 'utp.user_id', '=', 'm_users.id') + ->leftJoin('m_proyek', 'utp.proyek_id', '=', 'm_proyek.id') ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name', 'm_users.name AS join_first_name') ->get(); @@ -612,138 +601,160 @@ class ProjectController extends Controller return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); } + public function detail(Request $request, $id, $gantt_id = null, $s_curve = null) { - 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); - if (!isset($gantt_id)) { - $gantt = MasterFunctionsHelper::getLatestGantt($id); - $ganttId = $gantt['last_gantt_id']; - } else { - $ganttId = $gantt_id; - } - $result->projectManager = User::where('id', $result->pm_id)->value('name'); - - if (isset($s_curve)) { - $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->first(); - $actualStartExist = Activity::where('proyek_id', $id)->whereNotNull('actual_start')->exists(); - if ($result['type_proyek_id'] === 9) { - // $actualEndExist = Activity::where('proyek_id', $id)->exists(); - $query = Activity::where('proyek_id', $id); - $maxEndDate = Activity::where('proyek_id', $id)->select('end_date') - ->orderBy('end_date', 'desc') - ->first(); - } else { - // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); - $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') - ->orderBy('end_date', 'desc') - ->first(); - $query = Activity::where('version_gantt_id', $ganttId); - } - } else { - $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $ganttId)->first(); - $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); - // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); - $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') - ->orderBy('end_date', 'desc') - ->first(); - $query = Activity::where('version_gantt_id', $ganttId); - } - - if ($actualStartExist) { - $startDate = $query->orderBy('actual_start')->value('start_date'); - } else { - $startDate = $query->orderBy('start_date')->value('start_date'); - } - // if($actualEndExist) - // { - // // $maxEndDate = $query->max('id'); - // // get last end_date - // // $endDate = $query->where('id',$maxEndDate)->first()->end_date; + DB::beginTransaction(); + try { + 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); + } + if (!isset($gantt_id)) { + $gantt = MasterFunctionsHelper::getLatestGantt($id); + $ganttId = $gantt['last_gantt_id']; + } else { + $ganttId = $gantt_id; + } + $result->projectManager = User::where('id', $result->pm_id)->value('name'); + + if (isset($s_curve)) { + $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->first(); + $actualStartExist = Activity::where('proyek_id', $id)->whereNotNull('actual_start')->exists(); + if ($result['type_proyek_id'] === 9) { + // $actualEndExist = Activity::where('proyek_id', $id)->exists(); + $query = Activity::where('proyek_id', $id); + $maxEndDate = Activity::where('proyek_id', $id)->select('end_date') + ->orderBy('end_date', 'desc') + ->first(); + } else { + // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') + ->orderByDesc('end_date') + ->first(); + $query = Activity::where('version_gantt_id', $ganttId); + } + } else { + $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $ganttId)->first(); + $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); + // $actualEndExist = Activity::where('version_gantt_id', $ganttId)->exists(); + $maxEndDate = Activity::where('version_gantt_id', $ganttId)->select('end_date') + ->orderByDesc('end_date') + ->first(); + $query = Activity::where('version_gantt_id', $ganttId); + } - $plannedStart = Activity::where('version_gantt_id', $ganttId) - ->orderBy('planned_start') - ->value('planned_start'); - $plannedEnd = Activity::where('version_gantt_id', $ganttId) - ->orderByDesc('planned_end') - ->value('planned_end'); - if (isset($result->header)) { - $result->header->start_date = $startDate; - $result->header->end_date = $maxEndDate->end_date; - $result->header->planned_start = $plannedStart; - $result->header->planned_end = $plannedEnd; - } - return response()->json(['status' => 'success', 'code' => 200, 'data' => $result, 'gantt' => $ganttId], 200); + if ($actualStartExist) { + $startDate = $query->orderBy('actual_start')->value('start_date'); + } else { + $startDate = $query->orderBy('start_date')->value('start_date'); + } + // if($actualEndExist) + // { + // // $maxEndDate = $query->max('id'); + // // get last end_date + // // $endDate = $query->where('id',$maxEndDate)->first()->end_date; + + // } + + $plannedStart = Activity::where('version_gantt_id', $ganttId) + ->orderBy('planned_start') + ->value('planned_start'); + $plannedEnd = Activity::where('version_gantt_id', $ganttId) + ->orderByDesc('planned_end') + ->value('planned_end'); + if (isset($result->header)) { + $result->header->start_date = $startDate; + $result->header->end_date = $maxEndDate->end_date; + $result->header->planned_start = $plannedStart; + $result->header->planned_end = $plannedEnd; + } + DB::commit(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result, 'gantt' => $ganttId], 200); + } catch (\Throwable $th) { + DB::rollBack(); + } } public function getOverdueActivities(Request $request) { - $payload = $request->all(); - if (empty($payload['id']) || !is_int((int)$payload['id'])) - return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + DB::beginTransaction(); + try { + $payload = $request->all(); + if (empty($payload['id']) || !is_int((int)$payload['id'])) { + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + } - $result = Project::find($payload['id']); - - if (!$result) - return response()->json(['status' => 'failed', 'message' => 'Project not found!', 'code' => 404], 404); - //TODO possible overdue bug - $endDate = Activity::where('proyek_id', $payload['id']) - ->orderByDesc('end_date') - ->value('end_date'); - if (isset($payload['till_date'])) { - if (isset($payload['scurve'])) { - $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('m_activity.proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); - } else { - $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); - } - } else { - if (isset($payload['scurve'])) { - $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('m_activity.proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); - } else { - $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); - } - } - $result->overdueActivities = $overdueActivities; + $result = Project::find($payload['id']); - return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + if (!$result) { + return response()->json(['status' => 'failed', 'message' => 'Project not found!', 'code' => 404], 404); + } + //TODO possible overdue bug + $endDate = Activity::where('proyek_id', $payload['id']) + ->orderByDesc('end_date') + ->value('end_date'); + if (isset($payload['till_date'])) { + if (isset($payload['scurve'])) { + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('m_activity.proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); + } else { + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->whereDate('end_date', '<=', $endDate)->orderBy('end_date', 'asc')->get(); + } + } else { + if (isset($payload['scurve'])) { + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('m_activity.proyek_id', $payload['id'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); + } else { + $overdueActivities = Activity::join('m_version_gantt', 'm_activity.version_gantt_id', '=', 'm_version_gantt.id')->where('version_gantt_id', $payload['gantt'])->whereNotNull('parent_id')->where('persentase_progress', '!=', 100)->orderBy('end_date', 'asc')->get(); + } + } + $result->overdueActivities = $overdueActivities; + DB::commit(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } catch (\Throwable $th) { + DB::rollBack(); + } } public function getReportDistribution(Request $request) { - $payload = $request->all(); + DB::beginTransaction(); + try { + $payload = $request->all(); - if (empty($payload['project_id']) || !is_int((int)$payload['project_id'])) - return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + if (empty($payload['project_id']) || !is_int((int)$payload['project_id'])) { + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + } - $reports = DB::table('assign_material_to_activity as ama') - ->select( - 'u.name', - 'a.name as activity_name', - 'ama.qty_planning', - 'ram.qty as qty_real', - 'rm.description as material_name', - 'rm.uom as material_unit', - 'ram.lat', - 'ram.lon', - 'ram.description as report_notes', - 'ram.report_date' - ) - ->join('report_activity_material as ram', 'ram.assign_material_id', '=', 'ama.id') - ->join('m_req_material as rm', 'rm.id', '=', 'ama.material_id') - ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') - ->join('m_users as u', 'u.id', '=', 'ram.user_id') - ->where('ama.proyek_id', '=', $payload['project_id']) - ->whereNotNull('ram.lat') - ->whereBetween('ram.report_date', [$payload['start_date'], $payload['end_date']]); - - return response()->json(['status' => 'success', 'code' => 200, 'data' => $reports], 200); + $reports = AssignMaterial::query() + ->from('assign_material_to_activity AS ama') + ->select( + 'u.name', + 'a.name as activity_name', + 'ama.qty_planning', + 'ram.qty as qty_real', + 'rm.description as material_name', + 'rm.uom as material_unit', + 'ram.lat', + 'ram.lon', + 'ram.description as report_notes', + 'ram.report_date' + ) + ->join('report_activity_material as ram', 'ram.assign_material_id', '=', 'ama.id') + ->join('m_req_material as rm', 'rm.id', '=', 'ama.material_id') + ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') + ->join('m_users as u', 'u.id', '=', 'ram.user_id') + ->where('ama.proyek_id', '=', $payload['project_id']) + ->whereNotNull('ram.lat') + ->whereBetween('ram.report_date', [$payload['start_date'], $payload['end_date']]); + DB::commit(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $reports], 200); + } catch (\Throwable $th) { + DB::rollBack(); + } } public function getManpower($proyek_id) @@ -763,51 +774,59 @@ class ProjectController extends Controller public function dashboard($id) { - $data = DB::table('m_proyek as mp') - ->select( - 'mp.kode_sortname', - 'mp.nama as name_project', - 'mp.mulai_proyek as start', - 'mp.akhir_proyek as finish', - 'mp.rencana_biaya', - 'mp.company', - 'mp.currency_symbol', - 'mu.name as pm', - 'mp.budget_health' - ) - ->join('m_users as mu', 'mu.id', '=', 'mp.pm_id') - ->where('mp.id', $id) - ->first(); - - if (!$data) - return response()->json(['status' => 'failed', 'message' => 'Data tidak ditemukan!', 'code' => 404], 404); - - $manpowers = UserToProyek::where('proyek_id', $id)->count(); - $rootActivity = Activity::whereNull('parent_id')->where('proyek_id', $id)->orderBy('version_gantt_id', 'desc')->first(); - - $actualCost = @$rootActivity->biaya_actual ?? 0; - $progress = @$rootActivity->persentase_progress ?? 0; - - $commentActivity = DB::table('m_comment_activity as mca') - ->select( - 'mca.activity_id', - 'mca.comment as comment', - 'mca.created_by as comment_by', - 'mca.created_at as comment_created', - 'ma.name as activity' - ) - ->join('m_activity as ma', 'ma.id', '=', 'mca.activity_id') - ->where('ma.proyek_id', $id) - ->orderBy('comment_by') - ->take(2) - ->get(); - - $data->actual_cost = $actualCost; - $data->progress = $progress; - $data->comment = $commentActivity; - $data->man_power = $manpowers; + DB::beginTransaction(); + try { + $data = Project::query() + ->from('m_proyek AS mp') + ->select( + 'mp.kode_sortname', + 'mp.nama as name_project', + 'mp.mulai_proyek as start', + 'mp.akhir_proyek as finish', + 'mp.rencana_biaya', + 'mp.company', + 'mp.currency_symbol', + 'mu.name as pm', + 'mp.budget_health' + ) + ->join('m_users as mu', 'mu.id', '=', 'mp.pm_id') + ->where('mp.id', $id) + ->first(); + + if (!$data) { + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + } - return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + $manpowers = UserToProyek::where('proyek_id', $id)->count(); + $rootActivity = Activity::whereNull('parent_id')->where('proyek_id', $id)->orderByDesc('version_gantt_id')->first(); + + $actualCost = @$rootActivity->biaya_actual ?? 0; + $progress = @$rootActivity->persentase_progress ?? 0; + + $commentActivity = CommentActivity::query() + ->from('m_comment_activity AS mca') + ->select( + 'mca.activity_id', + 'mca.comment as comment', + 'mca.created_by as comment_by', + 'mca.created_at as comment_created', + 'ma.name as activity' + ) + ->join('m_activity as ma', 'ma.id', '=', 'mca.activity_id') + ->where('ma.proyek_id', $id) + ->orderBy('comment_by') + ->take(2) + ->get(); + + $data->actual_cost = $actualCost; + $data->progress = $progress; + $data->comment = $commentActivity; + $data->man_power = $manpowers; + DB::commit(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } catch (\Throwable $th) { + DB::rollBack(); + } } private function httpReq($search) From f723348bed2649997fc86814302322074a253ddc Mon Sep 17 00:00:00 2001 From: wahyuun Date: Fri, 15 Mar 2024 13:02:34 +0700 Subject: [PATCH 123/155] update type paket in company register --- app/Http/Controllers/UserRegisterController.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/UserRegisterController.php b/app/Http/Controllers/UserRegisterController.php index 1a31eaf..8b61abb 100644 --- a/app/Http/Controllers/UserRegisterController.php +++ b/app/Http/Controllers/UserRegisterController.php @@ -35,7 +35,7 @@ class UserRegisterController extends Controller $phone_no = $data['phone_no']; $email = $data['email']; $username = $data['username']; - $type_paket = $request->type_account === 'Personal' ? $data['type_paket'] : ''; + $type_paket = $data['type_paket']; $company_address = $request->type_account === 'Company' ? $data['companyAddress'] : ''; $full_name = $request->type_account === 'Personal' ? $data['full_name'] : ''; @@ -94,9 +94,7 @@ class UserRegisterController extends Controller if(empty($getMenu)) { return; } - if($request->type_account === 'Personal') { - $this->addTransaction((int)$addCompany['id'], $formDataCompany); - } + $this->addTransaction((int)$addCompany['id'], $formDataCompany); $addMenuCompany = $this->addMenuCompany($getMenu, (int)$addCompany['id']); if(empty($addMenuCompany)) { From f0e79dbaf45692d84c1fb10e26996d0a7cf267a4 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Fri, 15 Mar 2024 16:26:07 +0700 Subject: [PATCH 124/155] update directory company --- app/Http/Controllers/Controller.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index ce78741..255a081 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -45,10 +45,13 @@ class Controller extends BaseController protected function setCustomeDirectoryUpload($company_name) { - $pathImage = 'assets/' . $company_name . '/image/'; - $pathDocument = 'assets/' . $company_name . '/file/project/'; - $pathTmpImport = 'assets/' . $company_name . '/file/tmpimport/'; - $pathActivityDocument = 'assets/' . $company_name . '/file/activity/'; + $current_date = date('Y-m-d'); + [$year, $month, $day] = explode('-', $current_date); + + $pathImage = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/image/'; + $pathDocument = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/file/project/'; + $pathTmpImport = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/file/tmpimport/'; + $pathActivityDocument = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/file/activity/'; return [ 'pathImage' => $pathImage, From 0fd5e79d4acee78a7dcc5626374e69a11db3d641 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Tue, 19 Mar 2024 14:40:31 +0700 Subject: [PATCH 125/155] add endpoint all information company --- app/Http/Controllers/Controller.php | 29 ++++++++++++++++++---- app/Http/Controllers/ProjectController.php | 14 +++-------- routes/web.php | 1 + 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 255a081..181811a 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -10,6 +10,7 @@ use App\Models\Company; use App\Models\ReportK3Detail; use App\Models\UserToActivity; use App\Models\ProductTransaction; +use App\Models\Project; use Illuminate\Support\Facades\DB; use Carbon\Carbon; use Illuminate\Support\Facades\Http; @@ -64,14 +65,10 @@ class Controller extends BaseController public function storage($company_name) { $directory = 'assets/' . urldecode($company_name); - if (!is_dir($directory)) { return "Directory not found"; } - $size = 0; - - try { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) { $size += $file->getSize(); @@ -79,10 +76,32 @@ class Controller extends BaseController } catch (Exception $e) { return "Error while calculating size: " . $e->getMessage(); } - return round($size / 1048576, 2); } + public function storageAllCompany() + { + $companies = Company::get(); + $formData = []; + foreach($companies as $data) { + $size = 0; + $directory = 'assets/' . urldecode($data['company_name']); + if (is_dir($directory)) { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) { + $size += $file->getSize(); + } + } + $formData[] = [ + 'company_name' => $data['company_name'], + 'size' => round($size / 1048576, 2), + 'exp_ospro' => ProductTransaction::query()->where('company_id', $data['id'])->value('exp_ospro'), + 'project_total' => Project::query()->where('company_id',$data['id'])->count() + ]; + } + + return $formData; + } + public function setExpiredTimeOspro($company_id) { $currentDate = Carbon::now(); diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index bbad373..a5be020 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -84,17 +84,8 @@ class ProjectController extends Controller return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); } - // $result = Project::query() - // ->from('m_proyek AS mp') - // ->where('mp.id', $id) - // ->selectRaw('value_proyek,scoupe_of_work,kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek, - // area_kerja,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); - - // if (!is_null($result->first()['divisi_id'])) { - // $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') - // ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); - // } - $result = Project::select( + $result = Project:: + select( 'value_proyek', 'scoupe_of_work', 'kode_sortname', @@ -126,6 +117,7 @@ class ProjectController extends Controller 'phase_id', 'calculation_status', 'md.name as divisi_name', + 'm_proyek.company_id' ) ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') ->where('m_proyek.id', $id) diff --git a/routes/web.php b/routes/web.php index 221cbbb..0509a92 100644 --- a/routes/web.php +++ b/routes/web.php @@ -591,6 +591,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/demo-management/list', 'DemoController@list'); $router->get('/information-storage/{company_name}', 'Controller@storage'); + $router->get('/information-storage-all-company','Controller@storageAllCompany'); $router->post('/refferal-code/search', 'RefferalCodeController@search'); $router->post('/refferal-code/add', 'RefferalCodeController@add'); From dae02af02bc48a5defc6606d016a4d21497d62ef Mon Sep 17 00:00:00 2001 From: wahyuun Date: Wed, 20 Mar 2024 17:21:38 +0700 Subject: [PATCH 126/155] update folder asset --- app/Http/Controllers/Controller.php | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 181811a..7e00c15 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -46,13 +46,10 @@ class Controller extends BaseController protected function setCustomeDirectoryUpload($company_name) { - $current_date = date('Y-m-d'); - [$year, $month, $day] = explode('-', $current_date); - - $pathImage = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/image/'; - $pathDocument = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/file/project/'; - $pathTmpImport = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/file/tmpimport/'; - $pathActivityDocument = 'assets/' . $company_name . ' ' . $year . '-' . $month . '-' . $day . '/file/activity/'; + $pathImage = 'assets/' . $company_name . '/image/'; + $pathDocument = 'assets/' . $company_name . '/file/project/'; + $pathTmpImport = 'assets/' . $company_name . '/file/tmpimport/'; + $pathActivityDocument = 'assets/' . $company_name . '/file/activity/'; return [ 'pathImage' => $pathImage, From d74a6a0a1af1a508bab4dacb437a57bb42315810 Mon Sep 17 00:00:00 2001 From: wahyuun Date: Fri, 22 Mar 2024 10:02:34 +0700 Subject: [PATCH 127/155] adding is_customer fillable --- app/Models/HumanResource.php | 1 + app/Models/User.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Models/HumanResource.php b/app/Models/HumanResource.php index e1b3706..91ef5a5 100644 --- a/app/Models/HumanResource.php +++ b/app/Models/HumanResource.php @@ -36,5 +36,6 @@ class HumanResource extends Model 'updated_by', 'divisi_id', 'status_boundary', + 'is_customer' ]; } diff --git a/app/Models/User.php b/app/Models/User.php index 58b203b..7e2e9ac 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -24,7 +24,7 @@ class User extends Model implements AuthenticatableContract, AuthorizableContrac protected $fillable = [ 'name', 'email', 'role_id', 'username', 'session_login', 'phone_number', 'email', 'address', 'fcm_token', 'gender', 'birth_place', 'birth_date', 'blood_type', 'ktp_number', 'working_hours', - 'created_at', 'created_by', 'updated_at', 'updated_by', 'status_resource', 'discount_id','company_id' + 'created_at', 'created_by', 'updated_at', 'updated_by', 'status_resource', 'discount_id','company_id','is_customer' ]; const CREATED_AT = 'created_at'; From 90780aec4a770edcf618ec0014ba1b00a6c9a0f8 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:37:24 +0700 Subject: [PATCH 128/155] update uploadTmpImport --- app/Http/Controllers/ActivityController.php | 29 ++++++++++++++++----- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index 55e0444..a804f8a 100755 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -21,6 +21,7 @@ use App\Models\ProductTransaction; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use App\Helpers\MasterFunctionsHelper; +use Carbon\Carbon; class ActivityController extends Controller { @@ -1126,33 +1127,49 @@ class ActivityController extends Controller public function uploadTmpImport(Request $request) { + DB::beginTransaction(); if ($request->hasFile('dokumen')) { $document = $request->file('dokumen'); $gantt_id = $request->gantt_id; - $name = $document->getClientOriginalName(); + $timeNow = Carbon::now(); + + $originalFilename = $document->getClientOriginalName(); + $extension = pathinfo($originalFilename, PATHINFO_EXTENSION); + $filename = pathinfo($originalFilename, PATHINFO_FILENAME); + $name = $filename . '_' . $timeNow->format('d-m-y-His') . '.' . $extension; + // Limited Storage $company = Company::where('company_name', $request->company_name)->first(); if($company) { $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); - $getLimitStorage = $this->setLimitsStorage($company, $document, $name, $destinationPath['pathTmpImport'], $destinationPath); + $getLimitStorage = $this->setLimitsStorage($company, $document, $destinationPath['pathTmpImport'], $destinationPath); } - if (isset($getLimitStorage) && $getLimitStorage['resultMove']) { + if (isset($getLimitStorage)) { + if($getLimitStorage === false) { + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Limited storage maximum!', 'code' => 500], 500); + } + $data = [ 'gantt_id' => (int) $gantt_id, 'file' => $name, 'type_dokumen' => $request->type_dokumen ]; - $getLimitStorage['resultMove'] = TmpImport::create($data); + $result = TmpImport::create($data); - if (!$getLimitStorage['resultMove']) { - unlink($this->pathTmpImport . $name); + if (!$document->move($destinationPath['pathTmpImport'], $name) && $result) { + unlink($destinationPath['pathTmpImport'].$name); + DB::rollBack(); return response()->json(['status' => 'failed', 'message' => 'Upload failed!', 'code' => 500], 500); } + DB::commit(); return response()->json(['status' => 'success', 'message' => 'Upload successful!', 'code' => 200], 200); } + DB::rollBack(); return response()->json(['status' => 'failed', 'message' => 'Upload failed!', 'code' => 500], 500); } + DB::rollBack(); return response()->json(['status' => 'failed', 'message' => 'File is required!', 'code' => 400], 400); } From d58194a117f1b4cdd6e2215466034dc6da914063 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:38:33 +0700 Subject: [PATCH 129/155] update payload search --- app/Http/Controllers/Controller.php | 133 +++++++++++++++------------- 1 file changed, 71 insertions(+), 62 deletions(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 7e00c15..cb97af5 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -46,10 +46,14 @@ class Controller extends BaseController protected function setCustomeDirectoryUpload($company_name) { - $pathImage = 'assets/' . $company_name . '/image/'; - $pathDocument = 'assets/' . $company_name . '/file/project/'; - $pathTmpImport = 'assets/' . $company_name . '/file/tmpimport/'; - $pathActivityDocument = 'assets/' . $company_name . '/file/activity/'; + $current_date = date('Y-m-d'); + [$year, $month] = explode('-', $current_date); + $yearMonth = $year.'-'.$month; + + $pathImage = 'assets/' . $company_name .'/'. $yearMonth . '/image/'; + $pathDocument = 'assets/' . $company_name .'/'. $yearMonth . '/file/project/'; + $pathTmpImport = 'assets/' . $company_name .'/'. $yearMonth . '/file/tmpimport/'; + $pathActivityDocument = 'assets/' . $company_name .'/'. $yearMonth . '/file/activity/'; return [ 'pathImage' => $pathImage, @@ -118,75 +122,76 @@ class Controller extends BaseController } } - protected function setLimitsStorage($company, $dokumen, $name, $initPath, $destinatePath) + protected function setLimitsStorage($company, $dokumen, $initPath, $destinatePath) { - $totalSize = 0; - $sizeFile = $dokumen->getSize(); - // Path - $folderPath = $destinatePath['pathDocument']; - $folderPathImage = $destinatePath['pathImage']; - $folderPathTmpImport = $destinatePath['pathTmpImport']; - $folderPathActivityDocument = $destinatePath['pathActivityDocument']; - // Create Directory - if (!file_exists($initPath)) { - mkdir($initPath, 0777, true); - } - // Scanning & Existing Folder - if (file_exists($folderPathImage)) { - $files = scandir($folderPathImage); - foreach ($files as $file) { - if (is_file($folderPathImage . '/' . $file)) { - $totalSize += filesize($folderPathImage . '/' . $file); + $countCreate = false; + DB::transaction(function() use($company, $dokumen, $initPath, $destinatePath, &$countCreate) { + $totalSize = 0; + $sizeFile = $dokumen->getSize(); + // Path + $folderPath = $destinatePath['pathDocument']; + $folderPathImage = $destinatePath['pathImage']; + $folderPathTmpImport = $destinatePath['pathTmpImport']; + $folderPathActivityDocument = $destinatePath['pathActivityDocument']; + // Create Directory + if (!file_exists($initPath)) { + mkdir($initPath, 0777, true); + } + // Scanning & Existing Folder + if (file_exists($folderPathImage)) { + $files = scandir($folderPathImage); + foreach ($files as $file) { + if (is_file($folderPathImage . '/' . $file)) { + $totalSize += filesize($folderPathImage . '/' . $file); + } } } - } - if (file_exists($folderPath)) { - $filesImage = scandir($folderPath); - foreach ($filesImage as $file) { - if (is_file($folderPath . '/' . $file)) { - $totalSize += filesize($folderPath . '/' . $file); + if (file_exists($folderPath)) { + $filesImage = scandir($folderPath); + foreach ($filesImage as $file) { + if (is_file($folderPath . '/' . $file)) { + $totalSize += filesize($folderPath . '/' . $file); + } } } - } - if (file_exists($folderPathTmpImport)) { - $filesTmpImport = scandir($folderPathTmpImport); - foreach ($filesTmpImport as $file) { - if (is_file($folderPathTmpImport . '/' . $file)) { - $totalSize += filesize($folderPathTmpImport . '/' . $file); + if (file_exists($folderPathTmpImport)) { + $filesTmpImport = scandir($folderPathTmpImport); + foreach ($filesTmpImport as $file) { + if (is_file($folderPathTmpImport . '/' . $file)) { + $totalSize += filesize($folderPathTmpImport . '/' . $file); + } } } - } - if (file_exists($folderPathActivityDocument)) { - $filesActivityDocument = scandir($folderPathActivityDocument); - foreach ($filesActivityDocument as $file) { - if (is_file($folderPathActivityDocument . '/' . $file)) { - $totalSize += filesize($folderPathActivityDocument . '/' . $file); + if (file_exists($folderPathActivityDocument)) { + $filesActivityDocument = scandir($folderPathActivityDocument); + foreach ($filesActivityDocument as $file) { + if (is_file($folderPathActivityDocument . '/' . $file)) { + $totalSize += filesize($folderPathActivityDocument . '/' . $file); + } } } - } - // Logic - $totalSize += $sizeFile; - $transaction = ProductTransaction::query() - ->where('company_id', $company['id']); - $cloneQueryTransaction = clone $transaction; - $countCreate = false; - if ($transaction->where([['type_paket', 'Basic'], ['amount', '!=', null]])->exists()) { - $maximumSize = 500 * 1024 * 1024; - $countCreate = true; - } elseif ($cloneQueryTransaction->where([['type_paket', 'Free'], ['amount', 0]])->exists()) { - $maximumSize = 50 * 1024 * 1024; - $countCreate = true; - } - if ($countCreate) { - if ($totalSize > $maximumSize) { - return response()->json(['status' => 'failed', 'message' => 'Limited storage maximum!', 'code' => 500], 500); + // Logic + $totalSize += $sizeFile; + $transaction = ProductTransaction::query() + ->where('company_id', $company['id']); + $cloneQueryTransaction = clone $transaction; + if ($transaction->where([['type_paket', 'Basic'], ['amount', '!=', null]])->exists()) { + $maximumSize = 500 * 1024 * 1024; + $countCreate = true; + } elseif ($cloneQueryTransaction->where([['type_paket', 'Free'], ['amount', 0]])->exists()) { + $maximumSize = 50 * 1024 * 1024; + $countCreate = true; + } else { + $countCreate = true; } - } - $resultMove = $dokumen->move($initPath, $name); - return [ - 'resultMove' => $resultMove - ]; + if ($countCreate) { + if (floatval($totalSize) > floatval($maximumSize)) { + $countCreate = false; + } + } + }); + return $countCreate; } protected function setUpPayload($condition, $tableSelf) @@ -334,6 +339,10 @@ class Controller extends BaseController $query = $query->whereIn($tableColumn . "." . $column, $value); } else if ($operator == "notin") { $query = $query->whereNotIn($tableColumn . "." . $column, $value); + } else if ($operator == "isnull") { + $query = $query->WhereNull($tableColumn . "." . $column); + } else if ($operator == "notnull") { + $query = $query->WhereNotNull($tableColumn . "." . $column); } else { $query = $query->where($tableColumn . "." . $column, $operator, $value); } From ecc91e30a0c945950b9e677fe39c75116a2d6343 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:39:16 +0700 Subject: [PATCH 130/155] update condition --- app/Http/Controllers/ActivityDokumenController.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ActivityDokumenController.php b/app/Http/Controllers/ActivityDokumenController.php index 0cfd83b..4b3eaee 100644 --- a/app/Http/Controllers/ActivityDokumenController.php +++ b/app/Http/Controllers/ActivityDokumenController.php @@ -51,15 +51,16 @@ class ActivityDokumenController extends Controller $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); $result = $document->move($destinationPath['pathActivityDocument'], $name); } - if(!$result || !$company) + if(!$result || !$company) { 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 || !$company){ + if(!$result || !$company) { unlink($destinationPath['pathActivityDocument'].$name); return response()->json(['status'=>'failed','message'=>'Upload failed!','code'=> 500], 500); } From 977db0ec5a40867e54dba75865a9722dccd35836 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:39:48 +0700 Subject: [PATCH 131/155] update delete by folder --- .../FolderDocumentProyekController.php | 274 +++++++++--------- 1 file changed, 143 insertions(+), 131 deletions(-) diff --git a/app/Http/Controllers/FolderDocumentProyekController.php b/app/Http/Controllers/FolderDocumentProyekController.php index ed51469..ea46b8c 100644 --- a/app/Http/Controllers/FolderDocumentProyekController.php +++ b/app/Http/Controllers/FolderDocumentProyekController.php @@ -1,131 +1,143 @@ -validate($request, [ - 'name_folder' => 'required', - 'proyek_id' => 'required' - ]); - $data = $request->all(); - $data['created_by'] = $this->currentName; - - $result = FolderDocumentProyek::create($data); - if($result){ - return response()->json(['status'=>'success','message'=>'Folder Document Proyek successfull created','code'=>200]); - }else{ - return response()->json(['status'=>'failed','message'=>'Folder Document Proyek 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 = FolderDocumentProyek::find($id); - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'Data Folder Document Proyek not found!','code'=>400], 400); - die(); - } - - if($result){ - return response()->json(['status'=>'success','message'=>'Folder Document Proyek successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Folder Document Proyek failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = FolderDocumentProyek::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data Folder Document Proyek not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'Folder Document Proyek successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Folder Document Proyek failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_FolderDocumentProyek'); - $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 = FolderDocumentProyek::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 getTree($id) - { - $data = FolderDocumentProyek::where('proyek_id', $id)->whereNull('parent_id')->orderByRaw('id ASC')->get(); - $dataFile = DokumenProject::where('type_dokumen', 'project-document-out-folder')->where('ref_id', $id)->orderByRaw('id ASC')->get(); - $finalData = []; - foreach($data as $objRow){ - $objRow->children = $this->getChildren($id, $objRow->id); - $objRow->key = rand(1, 1000); - $objRow->isDir = true; - $finalData[] = $objRow; - } - - foreach($dataFile as $objRowFile) { - $objRowFile->key = rand(1, 1000); - $objRowFile->isDir = false; - $objRowFile->proyek_id = $id; - $finalData[] = $objRowFile; - } - - return response()->json(['status'=>'success','data'=>$finalData,'code'=>200], 200); - } - - private function getChildren($proyek_id, $parent_id) - { - $finalData = []; - $data = FolderDocumentProyek::where('proyek_id', $proyek_id)->where('parent_id', $parent_id)->orderByRaw('id ASC')->get(); - $dataFile = DokumenProject::where('type_dokumen', 'project-document-in-folder')->where('ref_id', $parent_id)->orderByRaw('id ASC')->get(); - foreach($data as $objRow){ - $objRow->key = rand(1, 1000); - $objRow->children = $this->getChildren($proyek_id, $objRow->id); - $objRow->isDir = true; - $finalData[] = $objRow; - } - - foreach($dataFile as $objRowFile) { - $objRowFile->key = rand(1, 1000); - $objRowFile->isDir = false; - $objRowFile->proyek_id = $proyek_id; - $finalData[] = $objRowFile; - } - - return $finalData; - } -} +validate($request, [ + 'name_folder' => 'required', + 'proyek_id' => 'required' + ]); + $data = $request->all(); + $data['created_by'] = $this->currentName; + + $result = FolderDocumentProyek::create($data); + if($result){ + return response()->json(['status'=>'success','message'=>'Folder Document Proyek successfull created','code'=>200]); + }else{ + return response()->json(['status'=>'failed','message'=>'Folder Document Proyek 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 = FolderDocumentProyek::find($id); + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'Data Folder Document Proyek not found!','code'=>400], 400); + die(); + } + + if($result){ + return response()->json(['status'=>'success','message'=>'Folder Document Proyek successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'Folder Document Proyek failed updated!','code'=>400], 400); + } + } + + public function delete($id, $company_id) + { + DB::beginTransaction(); + $data = FolderDocumentProyek::find($id); + $company = Company::find($company_id); + if($data && $company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $dir = $destinationPath['pathDocument']; + $dataFile = DokumenProject::where([['type_dokumen', 'project-document-in-folder'],['ref_id', $data['id']]])->orderByRaw('id ASC')->get(); + if (is_dir($dir)) { + foreach ($dataFile as $file) { + unlink($dir.$file['file']); + } + } + if($data->delete()) { + DB::commit(); + return response()->json(['status'=>'success','message'=>'Folder Document Proyek successfully deleted!','code'=>200], 200); + } else { + DB::rollBack(); + return response()->json(['status'=>'failed','message'=>'Folder Document Proyek failed deleted!','code'=>400], 400); + } + } else { + DB::rollBack(); + return response()->json(['status'=>'failed','message'=>'Data Folder Document Proyek not found!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_FolderDocumentProyek'); + $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 = FolderDocumentProyek::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 getTree($id) + { + $data = FolderDocumentProyek::where('proyek_id', $id)->whereNull('parent_id')->orderByRaw('id ASC')->get(); + $dataFile = DokumenProject::where('type_dokumen', 'project-document-out-folder')->where('ref_id', $id)->orderByRaw('id ASC')->get(); + $finalData = []; + foreach($data as $objRow){ + $objRow->children = $this->getChildren($id, $objRow->id); + $objRow->key = rand(1, 1000); + $objRow->isDir = true; + $finalData[] = $objRow; + } + + foreach($dataFile as $objRowFile) { + $objRowFile->key = rand(1, 1000); + $objRowFile->isDir = false; + $objRowFile->proyek_id = (int)$id; + $finalData[] = $objRowFile; + } + + return response()->json(['status'=>'success','data'=>$finalData,'code'=>200], 200); + } + + private function getChildren($proyek_id, $parent_id) + { + $finalData = []; + $data = FolderDocumentProyek::where('proyek_id', $proyek_id)->where('parent_id', $parent_id)->orderByRaw('id ASC')->get(); + $dataFile = DokumenProject::where('type_dokumen', 'project-document-in-folder')->where('ref_id', $parent_id)->orderByRaw('id ASC')->get(); + foreach($data as $objRow){ + $objRow->key = rand(1, 1000); + $objRow->children = $this->getChildren($proyek_id, $objRow->id); + $objRow->isDir = true; + $finalData[] = $objRow; + } + + foreach($dataFile as $objRowFile) { + $objRowFile->key = rand(1, 1000); + $objRowFile->isDir = false; + $objRowFile->proyek_id = (int)$proyek_id; + $finalData[] = $objRowFile; + } + + return $finalData; + } +} From 3d7d02e246eb18e89465cf5888bfc0cf6728fb3d Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:41:57 +0700 Subject: [PATCH 132/155] update condition upload --- app/Http/Controllers/ImageController.php | 37 +++++++++++++++--------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/app/Http/Controllers/ImageController.php b/app/Http/Controllers/ImageController.php index aa8adbe..af18b45 100644 --- a/app/Http/Controllers/ImageController.php +++ b/app/Http/Controllers/ImageController.php @@ -6,11 +6,13 @@ use App\Models\Image; use App\Models\Company; use Illuminate\Http\Request; use App\Models\ProductTransaction; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; class ImageController extends Controller { public function uploadImage(Request $request){ - + DB::beginTransaction(); if($request->hasFile('files')){ $this->validate($request, [ @@ -27,9 +29,13 @@ class ImageController extends Controller $company = Company::where('company_name', $request->company_name)->first(); if($company) { $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); - $getLimitStorage = $this->setLimitsStorage($company, $dokumen, $name, $destinationPath['pathImage'], $destinationPath); + $getLimitStorage = $this->setLimitsStorage($company, $dokumen, $destinationPath['pathImage'], $destinationPath); } - if(isset($getLimitStorage) && $getLimitStorage['resultMove']) { + if(isset($getLimitStorage)) { + if($getLimitStorage === false) { + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Limited storage maximum!', 'code' => 500], 500); + } $data = [ 'ref_id' => (int)$ref_id, 'image' => $name, @@ -54,27 +60,30 @@ class ImageController extends Controller if($company && $category === 'company_logo_header') { $company->update([ - 'logo_header' => array('content'=>$name) + 'logo_header' => array('content' => $name) ]); } if($company && $category === 'company_favicon') { $company->update([ - 'favicon_image' => array('content'=>$name) + 'favicon_image' => array('content' => $name) ]); } - - if($result){ - return response()->json(['status'=>'success', "name_image"=>$name,'message'=>'image upload is successfully!','code'=>200], 200); - }else{ + if($dokumen->move($destinationPath['pathImage'], $name) && $result) { + DB::commit(); + return response()->json(['status' => 'success', "name_image" => $name,'message' => 'image upload is successfully!','code' => 200], 200); + } else { + DB::rollBack(); unlink($destinationPath['pathImage'].$name); - return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); + return response()->json(['status' => 'failed','message' => 'image upload is failed! pertama' ,'code' => 400], 400); } - }else{ - return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); + } else { + DB::rollBack(); + return response()->json(['status'=>'failed','message'=>'image upload is failed! kedua','code'=>400], 400); } - }else{ + } else { + DB::rollBack(); return response()->json(['status'=>'failed','message'=>'image is required!','code'=>400], 400); } } @@ -210,7 +219,7 @@ class ImageController extends Controller public function deleteByRef($id, $category, $company_id) { - $data = Image::where("ref_id", intval($id))->where("category", $category)->first(); + $data = Image::where("ref_id", (int)$id)->where("category", $category)->first(); $company = Company::find($company_id); if($data && $company){ $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); From fb96003fd194caa73bf277f7b6b23240cf8a8993 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:42:34 +0700 Subject: [PATCH 133/155] update delete & fillable --- app/Http/Controllers/ProjectController.php | 7 +++++-- app/Models/Project.php | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index a5be020..d293cab 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -13,6 +13,7 @@ use App\Models\{ReportActivityMaterial,ProjectToChecklistK3,FolderDocumentProyek use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\{Artisan,DB}; use App\Helpers\MasterFunctionsHelper; +use Carbon\Carbon; const API_GEOLOCATION = "https://nominatim.oslogdev.com/search/ADDR?format=json&addressdetails=1&limit=1"; @@ -178,9 +179,11 @@ class ProjectController extends Controller { DB::beginTransaction(); $data = Project::find($id); + $dateNow = Carbon::now(); if ($data) { - $this->deleteRelative($id, $company_id); - if ($data->delete()) { + // $this->deleteRelative($id, $company_id); + // if ($data->delete()) { + if ($data->update(['deleted_at' => $dateNow, 'deleted_by_id' => $this->currentId])) { DB::commit(); return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); } else { diff --git a/app/Models/Project.php b/app/Models/Project.php index cfd463f..63a1aaf 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -52,6 +52,8 @@ class Project extends Model 'updated_at', 'updated_by', 'created_by_id', - 'company_id' + 'company_id', + 'deleted_at', + 'deleted_by_id' ]; } From 5dadd294bf6a02da596e3b7f22f4b5ea44214b3b Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:42:56 +0700 Subject: [PATCH 134/155] update uploadProjectDokumen --- .../Controllers/ProjectDokumenController.php | 49 +++++++++++++------ 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/ProjectDokumenController.php b/app/Http/Controllers/ProjectDokumenController.php index d9e4f04..5f1e02f 100644 --- a/app/Http/Controllers/ProjectDokumenController.php +++ b/app/Http/Controllers/ProjectDokumenController.php @@ -2,10 +2,10 @@ namespace App\Http\Controllers; -use App\Models\Company; use Illuminate\Http\Request; -use App\Models\DokumenProject; -use App\Models\ProductTransaction; +use App\Models\{DokumenProject,Company}; +use Carbon\Carbon; +use Illuminate\Support\Facades\DB; class ProjectDokumenController extends Controller { @@ -35,8 +35,8 @@ class ProjectDokumenController extends Controller $company = Company::find($company_id); if($company) { $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); - if(file_exists($destinationPath['pathDocument'].$document->file)){ - unlink($destinationPath['pathDocument'].$document->file); + if(file_exists($destinationPath['pathDocument'].$document['file'])){ + unlink($destinationPath['pathDocument'].$document['file']); } } $document->delete(); @@ -45,33 +45,47 @@ class ProjectDokumenController extends Controller public function uploadProjectDokumen(Request $request) { + DB::beginTransaction(); + $timeNow = Carbon::now(); if($request->hasFile('dokumen')){ $document = $request->file('dokumen'); $ref_id = $request->ref_id; - $name = $document->getClientOriginalName(); - // Limited Storage - $company = Company::where('company_name', $request->company_name)->first(); + + $originalFilename = $document->getClientOriginalName(); + $extension = pathinfo($originalFilename, PATHINFO_EXTENSION); + $filename = pathinfo($originalFilename, PATHINFO_FILENAME); + $name = $filename . '_' . $timeNow->format('d-m-y-His') . '.' . $extension; + // Limited Storage + $company = Company::whereId($request->company_id)->first(); if($company) { $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); - $getLimitStorage = $this->setLimitsStorage($company, $document, $name, $destinationPath['pathDocument'],$destinationPath); + $getLimitStorage = $this->setLimitsStorage($company, $document, $destinationPath['pathDocument'],$destinationPath); } - if(isset($getLimitStorage) && $getLimitStorage['resultMove']) { + if(isset($getLimitStorage)) { + if($getLimitStorage === false) { + DB::rollBack(); + return response()->json(['status' => 'failed', 'message' => 'Limited storage maximum!', 'code' => 500], 500); + } $data = [ 'ref_id' => (int)$ref_id, 'file' => $name, 'type_dokumen' => isset($request->type_dokumen) ? $request->type_dokumen : 'project-document' ]; - $getLimitStorage['resultMove'] = DokumenProject::create($data); + $result = DokumenProject::create($data); - if(!$getLimitStorage['resultMove']){ + if(!$document->move($destinationPath['pathDocument'], $name) && $result) { unlink($destinationPath['pathDocument'].$name); + DB::rollBack(); return response()->json(['status'=>'failed','message'=>'Dokumen project gagal diupload!','code'=> 500], 500); } + DB::commit(); return response()->json(['status'=>'success','message'=>'Dokumen project berhasil diupload!','code'=>200], 200); } + DB::rollBack(); return response()->json(['status'=>'failed','message'=>'Dokumen project gagal diupload!','code'=> 500], 500); } + DB::rollBack(); return response()->json(['status'=>'failed','message'=>'File is required!','code'=>400], 400); } @@ -94,15 +108,18 @@ class ProjectDokumenController extends Controller } $document = DokumenProject::find($id); $company = Company::find($company_id); + if(!$document || !$company) { 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); + + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + $pathToFile = $destinationPath['pathDocument'].$document['file']; + + if(!file_exists($pathToFile)) { + return response()->json(['status'=>'failed','message'=>'Directory not found!','code'=> 404], 404); } if($company) { - $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); - $pathToFile = $destinationPath['pathDocument'].$document->file; $name = pathinfo($pathToFile, PATHINFO_FILENAME) . "." . pathinfo($pathToFile, PATHINFO_EXTENSION); } $headers = [ From 12283c5de50c4b274ebdee9115310b083544a0a6 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 10:43:12 +0700 Subject: [PATCH 135/155] add route --- routes/web.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routes/web.php b/routes/web.php index 0509a92..bb539c7 100644 --- a/routes/web.php +++ b/routes/web.php @@ -494,7 +494,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/folder-document-proyek/edit/{id}', 'FolderDocumentProyekController@edit'); $router->put('/folder-document-proyek/update/{id}', 'FolderDocumentProyekController@update'); $router->post('/folder-document-proyek/search', 'FolderDocumentProyekController@search'); - $router->delete('/folder-document-proyek/delete/{id}', 'FolderDocumentProyekController@delete'); + $router->delete('/folder-document-proyek/delete/{id}/{company_id}', 'FolderDocumentProyekController@delete'); $router->get('/folder-document-proyek/list', 'FolderDocumentProyekController@list'); $router->get('/folder-document-proyek/get-tree/{id}', 'FolderDocumentProyekController@getTree'); From 6c9cee59ff7fef0788ae4b9c94534f91a7bec7c6 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 2 Apr 2024 13:21:02 +0700 Subject: [PATCH 136/155] add condition --- app/Http/Controllers/Controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index cb97af5..2b6aeb2 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -118,7 +118,7 @@ class Controller extends BaseController } return $countCreate; } else { - return $countCreate; + return $countCreate = true; } } From f60369a226ff6e49afa2a4049e4354df4ce5b76a Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Mon, 6 May 2024 08:35:22 +0700 Subject: [PATCH 137/155] fix(activity): param delete activity --- routes/web.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routes/web.php b/routes/web.php index bb539c7..840db36 100644 --- a/routes/web.php +++ b/routes/web.php @@ -272,7 +272,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->get('/task/edit/{id}', 'ActivityController@edit'); $router->put('/task/{id}', 'ActivityController@update'); $router->put('/task/update-regular/{id}', 'ActivityController@updateRegular'); - $router->delete('/task/{id}/{company_id}', 'ActivityController@delete'); + $router->delete('/task/{id}', 'ActivityController@delete'); $router->get('/task/get-update/{id}', 'ActivityController@getUpdate'); $router->post('/tmp-import/upload', 'ActivityController@uploadTmpImport'); From aa6538153c2453fd23bdfadcaee9f2fa54af58c9 Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Mon, 6 May 2024 08:35:43 +0700 Subject: [PATCH 138/155] feat: add fillable --- app/Models/ProjectType.php | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/app/Models/ProjectType.php b/app/Models/ProjectType.php index f6e9604..e3f1dff 100644 --- a/app/Models/ProjectType.php +++ b/app/Models/ProjectType.php @@ -1,17 +1,17 @@ - Date: Mon, 6 May 2024 08:36:36 +0700 Subject: [PATCH 139/155] fix(activity): fixed activity delete --- app/Http/Controllers/ActivityController.php | 50 ++++++++++++++------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index a804f8a..2571438 100755 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -629,32 +629,48 @@ class ActivityController extends Controller return response()->json(['status' => 'success', 'message' => 'Activity Updated!', 'code' => 200], 200); } - public function delete($id, $company_id) + public function delete($id) { - if (!$data = Activity::find($id)) + DB::beginTransaction(); + $activity_id = (int)$id; + $data = Activity::query() + ->from('m_activity as ma') + ->select('mp.company_id') + ->join('m_proyek as mp','ma.proyek_id','mp.id') + ->where('ma.id', $activity_id); + $cloneQuery = clone $data; + if (!$data->exists()) { + DB::rollBack(); return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 404], 404); - $this->deleteRelative($id, $company_id); - if (!$data->delete()) - return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'data activity failed deleted!', 'code' => 500], 500); + } + + $this->deleteRelative($activity_id, $cloneQuery->first()->company_id); - return response()->json(['status' => 'success', "action" => "deleted", 'message' => 'data activity successfully deleted!', 'code' => 200], 200); + if (!$data->delete()) { + DB::rollBack(); + return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data activity failed deleted!', 'code' => 500], 500); + } + DB::commit(); + return response()->json(['status' => 'success', "action" => "deleted", 'message' => 'Data activity successfully deleted!', 'code' => 200], 200); } private function deleteRelative($activity_id, $company_id) { - UserToActivity::where('activity_id', $activity_id)->delete(); - AssignMaterial::where('activity_id', $activity_id)->delete(); - $dataAd = ActivityDokumen::where("activity_id", $activity_id)->get(); - $company = Company::find($company_id); - if($company) { - $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); - foreach ($dataAd as $ad) { - if (file_exists($destinationPath['pathActivityDocument'] . $ad->file)) { - unlink($destinationPath['pathActivityDocument'] . $ad->file); + DB::transaction(function() use($activity_id, $company_id) { + UserToActivity::where('activity_id', $activity_id)->delete(); + AssignMaterial::where('activity_id', $activity_id)->delete(); + $dataAd = ActivityDokumen::where("activity_id", $activity_id)->get(); + $company = Company::find($company_id); + if($company) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + foreach ($dataAd as $ad) { + if (file_exists($destinationPath['pathActivityDocument'] . $ad->file)) { + unlink($destinationPath['pathActivityDocument'] . $ad->file); + } } + ActivityDokumen::where("activity_id", $activity_id)->delete(); } - ActivityDokumen::where("activity_id", $activity_id)->delete(); - } + }); } public function getUpdate($id) From 4a4e912ed06dd9480d3ffdd5f92f29a41c0905a2 Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Mon, 6 May 2024 08:37:04 +0700 Subject: [PATCH 140/155] fix(project): fixed project delete --- app/Http/Controllers/ProjectController.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index d293cab..f644ed2 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -181,9 +181,9 @@ class ProjectController extends Controller $data = Project::find($id); $dateNow = Carbon::now(); if ($data) { - // $this->deleteRelative($id, $company_id); - // if ($data->delete()) { - if ($data->update(['deleted_at' => $dateNow, 'deleted_by_id' => $this->currentId])) { + $this->deleteRelative($id, $company_id); + if ($data->delete()) { + // if ($data->update(['deleted_at' => $dateNow, 'deleted_by_id' => $this->currentId])) { DB::commit(); return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); } else { From ed924c78593ec2c2de12cfc2c4b45e83ba157d28 Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Mon, 6 May 2024 08:37:31 +0700 Subject: [PATCH 141/155] fix(maximum size): fixed condition maximum size --- app/Http/Controllers/Controller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 2b6aeb2..3e82edd 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -185,7 +185,7 @@ class Controller extends BaseController $countCreate = true; } - if ($countCreate) { + if ($countCreate && isset($maximumSize)) { // kondisi $maximumSize sementara karena blm ada paket enterprise if (floatval($totalSize) > floatval($maximumSize)) { $countCreate = false; } From 45f15cb129c6353a0682c60df6ec108959f21c19 Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Mon, 6 May 2024 08:38:03 +0700 Subject: [PATCH 142/155] fix(login): fixed login condition --- app/Http/Controllers/AuthController.php | 26 ++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index fbb2e3b..292670a 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -35,14 +35,18 @@ class AuthController extends Controller return response()->json(['status' => 'error', 'message' => 'You must fill all the fields'], 400); } - if (User::where('username', $username)->exists()) { + $userQuery = User::query() + ->where('username',$username); + + if ($userQuery->exists()) { $usernameCheck = true; - } - if (User::where('password', md5($password))->exists()) { - $passwordCheck = true; + $passwordValue = $userQuery->first()->password; + if($passwordValue === md5($password)) { + $passwordCheck = true; + } } - if ($usernameCheck & $passwordCheck) { + if ($usernameCheck && $passwordCheck) { $user = User::where([['username', $username],['password', md5($password)]])->first(); $checkExpiredOspro = $this->setExpiredTimeOspro($user['company_id']); if($checkExpiredOspro === false && $user['company_id'] != null) { @@ -113,14 +117,10 @@ class AuthController extends Controller ), ]); } else { - if (!$usernameCheck && !$passwordCheck) { - return response()->json(['code' => 201, 'message' => "Username and password doesn't match"], 201); - } - if (!$passwordCheck) { - return response()->json(['code' => 201, 'message' => "Password doesn't match"], 201); - } - if (!$usernameCheck) { - return response()->json(['code' => 201, 'message' => "Username doesn't match"], 201); + if (!$usernameCheck || !$passwordCheck) { + return response()->json(['code' => 201, 'message' => "Username or password doesn't match"], 201); + } else { + return response()->json(['code' => 500, 'message' => "Server error"], 500); } } } From 1a78790efcd98b5c425f0f307de84a8a1bfd2dfa Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Mon, 6 May 2024 08:38:47 +0700 Subject: [PATCH 143/155] fix(user proyek): fixed join --- app/Http/Controllers/UserToActivityController.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index 5313b5d..a17fdad 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -153,6 +153,7 @@ class UserToActivityController extends Controller $builder->groupBy("selfTable.start_date"); $builder->groupBy("selfTable.end_date"); $builder->groupBy("assign_material_to_activity.qty_planning"); + $builder->groupBy("assign_material_to_activity.id"); $builder->groupBy("m_version_gantt.name_version"); $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); From 1c74aaf3026e4893d435e389d504bf816e498a9c Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Mon, 6 May 2024 08:39:04 +0700 Subject: [PATCH 144/155] fix: clear comment --- .../Controllers/DashboardBoDController.php | 67 ++++++++++--------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index f1c8e16..ef211cb 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -262,7 +262,6 @@ class DashboardBoDController extends Controller foreach ($projects as $project) { $resp = null; if ($project->kode_sortname != "") { - // $resp = $this->getInvoiceIntegration($project->kode_sortname); array_push($return, [ 'project' => $project->nama, 'project_code' => $project->kode_sortname, @@ -281,22 +280,28 @@ class DashboardBoDController extends Controller public function getTotalProjectPerScheduleHealth($role_name, $company_id, $all_project, $hierarchy) { $role = urldecode($role_name); + $replaceHierarchy = preg_replace('/[\[\]]/', '', $hierarchy); $return = [ 'behind-schedule' => 0, 'warning' => 0, 'on-schedule' => 0, ]; + $divisi = Divisi::query() + ->where('company_id',$company_id) + ->pluck('id'); $projects = null; if ($role === 'Super Admin') { $projects = Project::get(); - } elseif ($all_project) { - $projects = Project::where('company_id', $company_id) - ->get(); + } elseif ($all_project == 'true') { + $projects = Project::whereIn('divisi_id',$divisi) + ->where('company_id', $company_id) + ->get(); } else { - $projects = Project::where('created_by_id', $hierarchy) - ->get(); + $projects = Project::whereIn('divisi_id',$divisi) + ->where('created_by_id', $replaceHierarchy) + ->get(); } foreach ($projects as $index => $project) { @@ -386,6 +391,8 @@ class DashboardBoDController extends Controller public function getTotalProjectPerBudgetHealth($role_name, $company_id, $all_project, $hierarchy) { $role = urldecode($role_name); + $replaceHierarchy = preg_replace('/[\[\]]/', '', $hierarchy); + $response = [ 'data' => [ 'overrun' => 0, @@ -393,43 +400,47 @@ class DashboardBoDController extends Controller 'on-budget' => 0, ] ]; + $divisi = Divisi::query() + ->where('company_id',$company_id) + ->pluck('id'); + // arr overrun if ($role === 'Super Admin') { $response['data']['overrun'] = Project::where('budget_health', 'overrun') ->count(); - } elseif ($all_project) { - $response['data']['overrun'] = Project::where('budget_health', 'overrun') - ->where('company_id', $company_id) + } elseif ($all_project == 'true') { + $response['data']['overrun'] = Project::whereIn('divisi_id',$divisi) + ->where([['budget_health', 'overrun'],['company_id', $company_id]]) ->count(); } else { - $response['data']['overrun'] = Project::where('budget_health', 'overrun') - ->where('created_by_id', $hierarchy) + $response['data']['overrun'] = Project::whereIn('divisi_id',$divisi) + ->where([['budget_health', 'overrun'],['created_by_id', $replaceHierarchy]]) ->count(); } - + // arr warning if ($role === 'Super Admin') { - $response['data']['overrun'] = Project::where('budget_health', 'warning') - ->count(); - } elseif ($all_project) { $response['data']['warning'] = Project::where('budget_health', 'warning') - ->where('company_id', $company_id) + ->count(); + } elseif ($all_project == 'true') { + $response['data']['warning'] = Project::whereIn('divisi_id',$divisi) + ->where([['budget_health', 'warning'],['company_id', $company_id]]) ->count(); } else { - $response['data']['warning'] = Project::where('budget_health', 'warning') - ->where('created_by_id', $hierarchy) + $response['data']['warning'] = Project::whereIn('divisi_id',$divisi) + ->where([['budget_health', 'warning'],['created_by_id', $replaceHierarchy]]) ->count(); } + // arr on-budget if ($role === 'Super Admin') { - Log::info('on-budget'); $response['data']['on-budget'] = Project::where('budget_health', 'on-budget') ->count(); - } elseif ($all_project) { - $response['data']['on-budget'] = Project::where('budget_health', 'on-budget') - ->where('company_id', $company_id) + } elseif ($all_project == 'true') { + $response['data']['on-budget'] = Project::whereIn('divisi_id',$divisi) + ->where([['company_id', $company_id],['budget_health', 'on-budget']]) ->count(); } else { - $response['data']['on-budget'] = Project::where('budget_health', 'on-budget') - ->where('created_by_id', $hierarchy) + $response['data']['on-budget'] = Project::whereIn('divisi_id',$divisi) + ->where([['budget_health', 'on-budget'],['created_by_id', $replaceHierarchy]]) ->count(); } return response()->json($response, 200); @@ -437,10 +448,8 @@ class DashboardBoDController extends Controller private function countTotalProjectByBudgetHealthInDivision($divisi, $health) { - return Project::where('divisi_id', $divisi) - /* ->orWhere('akhir_proyek', 'like', $year) */ - ->where('budget_health', $health) - ->count(); + $project = Project::where([['divisi_id', $divisi],['budget_health', $health]])->count(); + return $project; } @@ -476,8 +485,6 @@ class DashboardBoDController extends Controller unset($division->children); $division->budgetData = $budgetData; } - foreach ($divisions as $division) { - } return response()->json([ 'data' => [ $divisions From 02078e3a91d4a852a6c6768d3e643605e8efb381 Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Tue, 7 May 2024 15:30:24 +0700 Subject: [PATCH 145/155] fix(report): add param delete report by company --- routes/web.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routes/web.php b/routes/web.php index 840db36..9037b16 100644 --- a/routes/web.php +++ b/routes/web.php @@ -431,7 +431,7 @@ $router->group(['prefix' => 'api', 'middleware' => 'cors'], function () use ($ro $router->post('/report-activity-material/add', 'ReportActivityMaterialController@add'); $router->post('/report-activity-material/search', 'ReportActivityMaterialController@search'); - $router->delete('/report-activity-material/delete/{id}', 'ReportActivityMaterialController@delete'); + $router->delete('/report-activity-material/delete/{id}/{company_id}', 'ReportActivityMaterialController@delete'); $router->get('/report-activity-material/list', 'ReportActivityMaterialController@list'); $router->get('/report-activity-material/datatables', 'ReportActivityMaterialController@datatables'); $router->post('/report-activity-material/update-status', 'ReportActivityMaterialController@updateStatusStartFinish'); From bf3cc0fa7910c1b23afe07b99a44ba4ff5fab0ca Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Tue, 7 May 2024 15:31:00 +0700 Subject: [PATCH 146/155] fix(report): fixed delete report for image --- .../ReportActivityMaterialController.php | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index 62e08f3..403fdbd 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -8,6 +8,8 @@ use Illuminate\Support\Facades\DB; use App\Models\ReportActivityMaterial; use App\Models\Activity; use App\Models\AssignMaterial; +use App\Models\Company; +use App\Models\Image; use Yajra\Datatables\Datatables; use DateTime; @@ -100,10 +102,19 @@ class ReportActivityMaterialController extends Controller } } - public function delete($id) + public function delete($id, $company_id) { - if(!ReportActivityMaterial::findOrFail($id)->delete()) + $data = ReportActivityMaterial::findOrFail($id); + $company = Company::find($company_id); + $image = Image::where([['ref_id', $id],['category','report_activity']])->first(); + + if($data && $company && $image) { + $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); + unlink($destinationPath['pathImage'].$image['image']); + } + if(!$data->delete()) { return response()->json(['status'=>'failed','message'=>'Failed to deleted the data!','code'=> 500], 500); + } return response()->json(['status'=>'success','message'=> 'Data deleted!','code'=>200], 200); } From d40747ef3ded43fb267c864f92080da3a4ac351e Mon Sep 17 00:00:00 2001 From: Watiah11 Date: Fri, 10 May 2024 15:31:41 +0700 Subject: [PATCH 147/155] fix: role menu --- app/Http/Controllers/RoleMenuController.php | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/app/Http/Controllers/RoleMenuController.php b/app/Http/Controllers/RoleMenuController.php index 2a67fca..e8073d9 100644 --- a/app/Http/Controllers/RoleMenuController.php +++ b/app/Http/Controllers/RoleMenuController.php @@ -5,25 +5,28 @@ namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Menu; use App\Models\RoleMenu; +use Illuminate\Support\Facades\Log; class RoleMenuController extends Controller { public function add(Request $request) { $this->validate($request, [ - 'role_id' => 'required', - 'menu_id' => 'required', + 'role_id.*' => 'required', + 'menu_id.*' => 'required' ]); $data = $request->all(); - $data['created_by'] = $this->currentName; - - $result = RoleMenu::create($data); - - if($result){ + $countData = 0; + foreach($data as $arrData) { + $arrData['created_by'] = $this->currentName; + $result = RoleMenu::create($arrData); + $countData++; + } + if($result && $countData > 0) { return response()->json(['status'=>'success','message'=>'add data role menu successfully!','code'=>200], 200); - }else{ + } else { return response()->json(['status'=>'failed','message'=>'add data role menu failed!','code'=>400], 400); } } From 1fffcd4fd5d72dd21a161d11b33f09b508aa6759 Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 14 May 2024 14:46:23 +0700 Subject: [PATCH 148/155] feat: adding transaction in company management --- app/Http/Controllers/CompanyController.php | 61 ++++++++++++++++++---- 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index b828469..67338d3 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -5,6 +5,8 @@ namespace App\Http\Controllers; use App\Models\{User, RoleMenu, Role, ProductTransaction, MenuCompany, Company}; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\File; +use Carbon\Carbon; class CompanyController extends Controller { @@ -14,7 +16,9 @@ class CompanyController extends Controller 'company_name' => 'required', 'registration_no' => 'required', 'template_id' => 'required', - 'is_active' => 'required' + 'is_active' => 'required', + 'type_paket' => 'required|in:Free,Basic', + 'base_url' => 'required' ]); $data = $request->all(); @@ -24,11 +28,12 @@ class CompanyController extends Controller $data['base_url'] = json_encode($data['base_url'], true); } $result = Company::create($data); + $addTransaction = $this->addTransaction($result['id'],$data['type_paket']); - if ($result) { - return response()->json(['status' => 'success','data' => $result, 'message' => 'add Company successfully!', 'code' => 200], 200); + if ($result && $addTransaction) { + return response()->json(['status' => 'success','data' => $result, 'message' => 'Add Company successfully!', 'code' => 200], 200); } else { - return response()->json(['status' => 'failed', 'message' => 'add data Company failed!', 'code' => 400], 400); + return response()->json(['status' => 'failed', 'message' => 'Add data Company failed!', 'code' => 400], 400); } } @@ -62,11 +67,12 @@ class CompanyController extends Controller } if ($data) { $result = $data->update($request->all()); + $updateTransaction = $this->updateTransaction($id,$request->type_paket); } else { return response()->json(['status' => 'failed', 'message' => 'data Company not found!', 'code' => 400], 400); die(); } - if ($result) { + if ($result && $updateTransaction) { return response()->json(['status' => 'success', 'message' => 'data Company successfully updated!', 'code' => 200], 200); } else { return response()->json(['status' => 'failed', 'message' => 'data Company failed updated!', 'code' => 400], 400); @@ -78,7 +84,7 @@ class CompanyController extends Controller DB::beginTransaction(); $data = Company::find((int)$id); if ($data) { - $this->deleteRelative((int)$data['id']); + $this->deleteRelative($data); if ($data->delete()) { DB::commit(); return response()->json(['status' => 'success', 'message' => 'Data Company successfully deleted!', 'code' => 200], 200); @@ -93,18 +99,51 @@ class CompanyController extends Controller } } - private function deleteRelative($company_id) + private function deleteRelative($data) { - MenuCompany::where('company_id', $company_id)->delete(); - User::where('company_id', $company_id)->delete(); - $role = Role::where('company_id', $company_id)->first(); + $directory = 'assets/' . $data['company_name']; + if (is_dir($directory)) { + File::deleteDirectory($directory); + } + + MenuCompany::where('company_id', $data['id'])->delete(); + User::where('company_id', $data['id'])->delete(); + $role = Role::where('company_id', $data['id'])->first(); if ($role) { RoleMenu::where('role_id', $role->id)->delete(); $role->delete(); } - ProductTransaction::where('company_id', $company_id)->delete(); + ProductTransaction::where('company_id', $data['id'])->delete(); } + protected function addTransaction($id_company, $type_paket) + { + $currentDate = Carbon::now(); + $finalDate = $currentDate->copy()->addDays(30); + $formData = array( + 'company_id' => (int)$id_company, + 'type_paket' => $type_paket, + 'exp_ospro' => $finalDate, + 'amount' => $type_paket === 'Free' ? 0 : 250000 + ); + $result = ProductTransaction::create($formData); + if($result) { + return true; + } else { + return false; + } + } + + protected function updateTransaction($id_company, $type_paket) + { + $result = ProductTransaction::where('company_id', (int)$id_company)->first(); + $result->update(['type_paket' => $type_paket]); + if($result) { + return true; + } else { + return false; + } + } public function search(Request $request) { From ca2619ae08e067ca7b35dfd0820babfaddba00cb Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 14 May 2024 14:47:01 +0700 Subject: [PATCH 149/155] fix: fixed getSize in multiple upload --- app/Http/Controllers/ImageController.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/ImageController.php b/app/Http/Controllers/ImageController.php index af18b45..1e3c194 100644 --- a/app/Http/Controllers/ImageController.php +++ b/app/Http/Controllers/ImageController.php @@ -75,12 +75,12 @@ class ImageController extends Controller } else { DB::rollBack(); unlink($destinationPath['pathImage'].$name); - return response()->json(['status' => 'failed','message' => 'image upload is failed! pertama' ,'code' => 400], 400); + return response()->json(['status' => 'failed','message' => 'image upload is failed!' ,'code' => 400], 400); } } else { DB::rollBack(); - return response()->json(['status'=>'failed','message'=>'image upload is failed! kedua','code'=>400], 400); + return response()->json(['status'=>'failed','message'=>'image upload is failed!','code'=>400], 400); } } else { DB::rollBack(); @@ -105,7 +105,10 @@ class ImageController extends Controller $company = Company::where('company_name', $request->company_name)->first(); if($company) { $totalSize = 0; - $sizeFile = $dokumen->getSize(); + $sizeFile = 0; + foreach ($dokumen as $file) { + $sizeFile += $file->getSize(); + } $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); $folderPath = $destinationPath['pathImage']; @@ -114,7 +117,6 @@ class ImageController extends Controller } $files = scandir($folderPath); - $totalSize = 0; foreach ($files as $file) { if (is_file($folderPath . '/' . $file)) { From e09a0b11d20ba719ccbda9ac7f8bfe7b42c9c8bb Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 14 May 2024 14:47:31 +0700 Subject: [PATCH 150/155] fix: update type join --- app/Http/Controllers/ProjectController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index f644ed2..5e3e008 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -120,7 +120,7 @@ class ProjectController extends Controller 'md.name as divisi_name', 'm_proyek.company_id' ) - ->join('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') + ->leftJoin('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') ->where('m_proyek.id', $id) ->first(); if (!$result) { From 0491ff534e260d216616e45dfe0550581496a26e Mon Sep 17 00:00:00 2001 From: wahyun Date: Tue, 14 May 2024 22:22:08 +0700 Subject: [PATCH 151/155] feat: add enterprise in validation --- app/Http/Controllers/CompanyController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 67338d3..70280bf 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -17,7 +17,7 @@ class CompanyController extends Controller 'registration_no' => 'required', 'template_id' => 'required', 'is_active' => 'required', - 'type_paket' => 'required|in:Free,Basic', + 'type_paket' => 'required|in:Free,Basic,Enterprise', 'base_url' => 'required' ]); From d235b958758791e7a752b59d5def0748ff00ffe7 Mon Sep 17 00:00:00 2001 From: wahyun Date: Wed, 15 May 2024 12:08:38 +0700 Subject: [PATCH 152/155] fix: validation add & update --- app/Http/Controllers/HumanResourceController.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index 1cbee8b..14c44fa 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -3,7 +3,6 @@ namespace App\Http\Controllers; use App\Models\User; -use Illuminate\Support\Str; use App\Models\UserToProyek; use Illuminate\Http\Request; use App\Models\HumanResource; @@ -18,15 +17,15 @@ class HumanResourceController extends Controller public function add(Request $request) { $this->validate($request, [ - 'role_id' => 'required', 'name' => 'required', 'ktp_number' => 'required|string|unique:m_users,ktp_number', 'employee_type' => 'required', 'company_id' => 'required', - 'username' => 'unique:m_users,username' + 'username' => 'unique:m_users,username', ]); $data = $request->all(); + !$request->is_customer ? $this->validate($request,['role_id'=>'required','divisi_id'=>'required']) : ''; if (isset($request->password) && $request->password != "") { $data['password'] = md5($request->password); @@ -113,6 +112,8 @@ class HumanResourceController extends Controller public function update(Request $request, $id) { + !$request->is_customer ? $this->validate($request,['role_id'=>'required','divisi_id'=>'required']) : ''; + if (!$id || (int) $id < 0 || $id == "") { return response()->json(['status' => 'failed', 'message' => 'Id is required!', 'code' => 400], 400); } From 1c387c4b602e8ba939ed872144e95dbc6b711e1b Mon Sep 17 00:00:00 2001 From: wahyun Date: Thu, 16 May 2024 12:55:32 +0700 Subject: [PATCH 153/155] fix: handle validation add & update data --- .../Controllers/HumanResourceController.php | 59 +++++++++++-------- 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index 14c44fa..9e61237 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -2,12 +2,8 @@ namespace App\Http\Controllers; -use App\Models\User; -use App\Models\UserToProyek; use Illuminate\Http\Request; -use App\Models\HumanResource; -use App\Models\UserToActivity; -use App\Models\ProductTransaction; +use App\Models\{HumanResource,ProductTransaction,UserToActivity,UserToProyek,User}; use Illuminate\Support\Facades\Artisan; const URL_EMAIL = 'https://notifapp.odm-iu.com/service-mail/notif_mail.php'; @@ -16,29 +12,36 @@ class HumanResourceController extends Controller { public function add(Request $request) { + $messages = [ + 'ktp_number.unique' => 'Nomor KTP/ID Card tidak boleh sama', + 'username.unique' => 'Username tidak boleh sama', + 'required' => 'Data tidak boleh kosong' + ]; + $this->validate($request, [ - 'name' => 'required', + 'name' => 'required|string', 'ktp_number' => 'required|string|unique:m_users,ktp_number', - 'employee_type' => 'required', - 'company_id' => 'required', - 'username' => 'unique:m_users,username', - ]); + 'employee_type' => 'required|in:employee,subcon,freelance', + 'company_id' => 'required|integer', + 'username' => 'string|unique:m_users,username', + 'email' => 'string|unique:m_users,email' + ], $messages); $data = $request->all(); - !$request->is_customer ? $this->validate($request,['role_id'=>'required','divisi_id'=>'required']) : ''; + !$request->is_customer ? $this->validate($request,['role_id' => 'required','divisi_id' => 'required'], $messages) : ''; if (isset($request->password) && $request->password != "") { $data['password'] = md5($request->password); } $transaction = ProductTransaction::query() - ->where('company_id', $request->company_id); + ->where('company_id', (int) $request->company_id); $cloneQueryTransaction = clone $transaction; $countCreate = false; $projectResult = HumanResource::query() ->selectRaw('count(*) as total_hr') - ->where('company_id', $request->company_id) + ->where('company_id', (int) $request->company_id) ->first(); if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { if($projectResult['total_hr'] < 50) { @@ -67,6 +70,7 @@ class HumanResourceController extends Controller public function add_user(Request $request) { + $this->validate($request, [ 'role_id' => 'required', 'name' => 'required', @@ -111,12 +115,30 @@ class HumanResourceController extends Controller public function update(Request $request, $id) { + $messages = [ + 'ktp_number.unique' => 'Nomor KTP/ID Card tidak boleh sama', + 'username.unique' => 'Username tidak boleh sama', + 'required' => 'Data tidak boleh kosong' + ]; + + $request->validate($request, [ + 'name' => 'required|string', + 'ktp_number' => 'required|string|unique:m_users,ktp_number,'.$id . ',id', + 'employee_type' => 'required|in:employee,subcon,freelance', + 'company_id' => 'required|integer', + 'username' => 'unique:m_users,username,'.$id . ',id', + 'email' => 'string|unique:m_users,email,'.$id . ',id' + ], $messages); + + !$request->is_customer ? $this->validate($request,['role_id'=>'required', 'divisi_id'=>'required'], $messages) : ''; + $request->password ? $this->validate($request,['password'=>'required|min:8']) : ''; - !$request->is_customer ? $this->validate($request,['role_id'=>'required','divisi_id'=>'required']) : ''; + $data = $request->all(); if (!$id || (int) $id < 0 || $id == "") { return response()->json(['status' => 'failed', 'message' => 'Id is required!', 'code' => 400], 400); } + $humanresource = HumanResource::find($id); if(empty($humanresource)) { return response()->json(['status' => 'failed', 'message' => 'Data Human Resource not found!', 'code' => 400], 400); @@ -149,20 +171,11 @@ class HumanResourceController extends Controller } else { $countCreate = true; } - $request->ktp_number !== $humanresource['ktp_number'] ? $this->validate($request,['ktp_number'=>'unique:m_users,ktp_number|string']) : ''; - $request->email !== $humanresource['email'] ? $this->validate($request,['email'=>'unique:m_users,email|email']) : ''; - $request->password ? $this->validate($request,['password'=>'required|min:8']) : ''; - - $data = $request->all(); if (isset($request->password) && $request->password != "") { $data['password'] = md5($request->password); } - if (isset($data['username']) && HumanResource::where('username', $data['username'])->where('id', '<>', $id)->exists()) { - return response()->json(['status' => 'failed', 'message' => 'Username already exists!', 'code' => 400], 400); - } - if ($countCreate) { $result = $humanresource->update($data); } else { From 27a31dcd2bf022bf1eda438ccde6ccaa5446e783 Mon Sep 17 00:00:00 2001 From: farhantock Date: Sat, 18 May 2024 15:26:48 +0700 Subject: [PATCH 154/155] remove unused file --- .../Commands/syncHumanResourceIntegration.php | 77 ------------------- 1 file changed, 77 deletions(-) delete mode 100644 app/Console/Commands/syncHumanResourceIntegration.php diff --git a/app/Console/Commands/syncHumanResourceIntegration.php b/app/Console/Commands/syncHumanResourceIntegration.php deleted file mode 100644 index 7b4ef5f..0000000 --- a/app/Console/Commands/syncHumanResourceIntegration.php +++ /dev/null @@ -1,77 +0,0 @@ -message != 'success') - return; - - if(!is_int($response->total) || $response->total == 0) - return; - - $totalPage = $response->last_page; - echo "\nTotal Page = " . $totalPage; - $currentResponse = $response; - for($i = 1; $i <= $totalPage; $i++){ - echo "\nCurrent Page = " . $i; - $employeesPageData = $currentResponse->data; - foreach($employeesPageData as $employee){ - HumanResource::firstOrCreate( - ['ktp_number' => $employee->emp_id], - [ - 'name' => $employee->name, - 'employee_type' => 'employee', - 'status_resource' => 'active', - 'role_id' => 24, - 'created_by' => 'integration' - ], - ); - } - echo "\n------------------------------------------\n"; - $currentResponse = MasterFunctionsHelper::curlReq(str_replace('1', $i, $url)); - } - } -} From f19fc03276f6a868e7eba5e0b01e8d18a1575431 Mon Sep 17 00:00:00 2001 From: farhantock Date: Sat, 18 May 2024 15:27:02 +0700 Subject: [PATCH 155/155] fix(remove):adw integration --- app/Helpers/MasterFunctionsHelper.php | 24 - .../Controllers/DashboardBoDController.php | 97 +-- app/Http/Controllers/ProjectController.php | 601 +++++++++--------- .../Controllers/RequestMaterialController.php | 140 ++-- .../Controllers/UserToProyekController.php | 171 ++--- 5 files changed, 448 insertions(+), 585 deletions(-) diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index 14a759f..9a9b18e 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -12,30 +12,6 @@ use DateTime; class MasterFunctionsHelper { - public static function curlReq($url, $token = "") - { - if (!$token) - $token = config('api.adw_token'); - - $ch = curl_init(); - - curl_setopt($ch, CURLOPT_URL, $url); - $headers = [ - 'Authorization: ' . $token - ]; - - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_VERBOSE, true); - curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); - - $output = curl_exec($ch); - curl_close($ch); - - return json_decode($output); - } - public static function countDays($ganttId, $start, $end) { $dayOffs = VersionGantt::where('id', $ganttId)->first()->config_dayoff; diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index ef211cb..71e2daa 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -25,42 +25,7 @@ class DashboardBoDController extends Controller return $year; } - private function curlReq($url, $token) - { - $ch = curl_init(); - $headers = [ - 'Authorization: ' . $token - ]; - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - - $response = curl_exec($ch); - if ($response === false) - $response = curl_error($ch); - curl_close($ch); - - return json_decode($response); - } - - private function getInvoiceIntegration($search) - { - if (empty($search)) - return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); - if (empty($search)) - return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); - $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); - $token = config('api.adw_token'); - $response = $this->curlReq($url, $token); - - if (@$response->data->project_no == "") - if (@$response->data->project_no == "") - return null; - - return $response; - } public function getCompanyCashFlow($company_id, $all_project, $hierarchy, $role_name) { @@ -280,28 +245,28 @@ class DashboardBoDController extends Controller public function getTotalProjectPerScheduleHealth($role_name, $company_id, $all_project, $hierarchy) { $role = urldecode($role_name); - $replaceHierarchy = preg_replace('/[\[\]]/', '', $hierarchy); + $replaceHierarchy = preg_replace('/[\[\]]/', '', $hierarchy); $return = [ 'behind-schedule' => 0, 'warning' => 0, 'on-schedule' => 0, ]; - $divisi = Divisi::query() - ->where('company_id',$company_id) - ->pluck('id'); + $divisi = Divisi::query() + ->where('company_id', $company_id) + ->pluck('id'); $projects = null; if ($role === 'Super Admin') { $projects = Project::get(); } elseif ($all_project == 'true') { - $projects = Project::whereIn('divisi_id',$divisi) - ->where('company_id', $company_id) - ->get(); + $projects = Project::whereIn('divisi_id', $divisi) + ->where('company_id', $company_id) + ->get(); } else { - $projects = Project::whereIn('divisi_id',$divisi) - ->where('created_by_id', $replaceHierarchy) - ->get(); + $projects = Project::whereIn('divisi_id', $divisi) + ->where('created_by_id', $replaceHierarchy) + ->get(); } foreach ($projects as $index => $project) { @@ -391,7 +356,7 @@ class DashboardBoDController extends Controller public function getTotalProjectPerBudgetHealth($role_name, $company_id, $all_project, $hierarchy) { $role = urldecode($role_name); - $replaceHierarchy = preg_replace('/[\[\]]/', '', $hierarchy); + $replaceHierarchy = preg_replace('/[\[\]]/', '', $hierarchy); $response = [ 'data' => [ @@ -400,47 +365,47 @@ class DashboardBoDController extends Controller 'on-budget' => 0, ] ]; - $divisi = Divisi::query() - ->where('company_id',$company_id) - ->pluck('id'); + $divisi = Divisi::query() + ->where('company_id', $company_id) + ->pluck('id'); - // arr overrun + // arr overrun if ($role === 'Super Admin') { $response['data']['overrun'] = Project::where('budget_health', 'overrun') ->count(); } elseif ($all_project == 'true') { - $response['data']['overrun'] = Project::whereIn('divisi_id',$divisi) - ->where([['budget_health', 'overrun'],['company_id', $company_id]]) + $response['data']['overrun'] = Project::whereIn('divisi_id', $divisi) + ->where([['budget_health', 'overrun'], ['company_id', $company_id]]) ->count(); } else { - $response['data']['overrun'] = Project::whereIn('divisi_id',$divisi) - ->where([['budget_health', 'overrun'],['created_by_id', $replaceHierarchy]]) + $response['data']['overrun'] = Project::whereIn('divisi_id', $divisi) + ->where([['budget_health', 'overrun'], ['created_by_id', $replaceHierarchy]]) ->count(); } - // arr warning + // arr warning if ($role === 'Super Admin') { $response['data']['warning'] = Project::where('budget_health', 'warning') ->count(); } elseif ($all_project == 'true') { - $response['data']['warning'] = Project::whereIn('divisi_id',$divisi) - ->where([['budget_health', 'warning'],['company_id', $company_id]]) + $response['data']['warning'] = Project::whereIn('divisi_id', $divisi) + ->where([['budget_health', 'warning'], ['company_id', $company_id]]) ->count(); } else { - $response['data']['warning'] = Project::whereIn('divisi_id',$divisi) - ->where([['budget_health', 'warning'],['created_by_id', $replaceHierarchy]]) + $response['data']['warning'] = Project::whereIn('divisi_id', $divisi) + ->where([['budget_health', 'warning'], ['created_by_id', $replaceHierarchy]]) ->count(); } - // arr on-budget + // arr on-budget if ($role === 'Super Admin') { $response['data']['on-budget'] = Project::where('budget_health', 'on-budget') ->count(); } elseif ($all_project == 'true') { - $response['data']['on-budget'] = Project::whereIn('divisi_id',$divisi) - ->where([['company_id', $company_id],['budget_health', 'on-budget']]) + $response['data']['on-budget'] = Project::whereIn('divisi_id', $divisi) + ->where([['company_id', $company_id], ['budget_health', 'on-budget']]) ->count(); } else { - $response['data']['on-budget'] = Project::whereIn('divisi_id',$divisi) - ->where([['budget_health', 'on-budget'],['created_by_id', $replaceHierarchy]]) + $response['data']['on-budget'] = Project::whereIn('divisi_id', $divisi) + ->where([['budget_health', 'on-budget'], ['created_by_id', $replaceHierarchy]]) ->count(); } return response()->json($response, 200); @@ -448,8 +413,8 @@ class DashboardBoDController extends Controller private function countTotalProjectByBudgetHealthInDivision($divisi, $health) { - $project = Project::where([['divisi_id', $divisi],['budget_health', $health]])->count(); - return $project; + $project = Project::where([['divisi_id', $divisi], ['budget_health', $health]])->count(); + return $project; } diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 5e3e008..e1b1991 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -5,13 +5,44 @@ namespace App\Http\Controllers; use DateTime; use App\Jobs\ProcessSCurve; use Illuminate\Http\Request; -use App\Models\{ReportActivityMaterial,ProjectToChecklistK3,FolderDocumentProyek,ProjectParticipants,ProductTransaction,ProjectChecklists, - ProjectMileStone,RequestMaterial,ProjectApproval,CommentActivity,ActivityDokumen,UserToActivity,ShowHideColumn,ReportActivity,ProjectCharter,DokumenProject, - AssignMaterial,ProjectIssues,HierarchyFtth,VersionGantt,UserToProyek,ProjectRisks,ProjectPhase,ProjectType,OfficeHours,AssignTools,ReportK3,Activity,Project, - Holiday,Company,Image,User,Link +use App\Models\{ + ReportActivityMaterial, + ProjectToChecklistK3, + FolderDocumentProyek, + ProjectParticipants, + ProductTransaction, + ProjectChecklists, + ProjectMileStone, + RequestMaterial, + ProjectApproval, + CommentActivity, + ActivityDokumen, + UserToActivity, + ShowHideColumn, + ReportActivity, + ProjectCharter, + DokumenProject, + AssignMaterial, + ProjectIssues, + HierarchyFtth, + VersionGantt, + UserToProyek, + ProjectRisks, + ProjectPhase, + ProjectType, + OfficeHours, + AssignTools, + ReportK3, + Activity, + Project, + Holiday, + Company, + Image, + User, + Link }; use Illuminate\Database\Query\Builder; -use Illuminate\Support\Facades\{Artisan,DB}; +use Illuminate\Support\Facades\{Artisan, DB}; use App\Helpers\MasterFunctionsHelper; use Carbon\Carbon; @@ -20,17 +51,17 @@ const API_GEOLOCATION = "https://nominatim.oslogdev.com/search/ADDR?format=json& class ProjectController extends Controller { - public function add(Request $request) - { - $this->validate($request, [ - 'nama' => 'required', - 'mulai_proyek' => 'required', - 'mulai_proyek' => 'required', - 'akhir_proyek' => 'required', - 'rencana_biaya' => 'required', - 'type_proyek_id' => 'required', - 'company_id' => 'required' - ]); + public function add(Request $request) + { + $this->validate($request, [ + 'nama' => 'required', + 'mulai_proyek' => 'required', + 'mulai_proyek' => 'required', + 'akhir_proyek' => 'required', + 'rencana_biaya' => 'required', + 'type_proyek_id' => 'required', + 'company_id' => 'required' + ]); DB::beginTransaction(); try { $data = $request->all(); @@ -49,25 +80,25 @@ class ProjectController extends Controller ->selectRaw('count(*) as total_project') ->where('company_id', $request->company_id) ->first(); - if($transaction->where([['type_paket','Basic'],['amount','!=',null]])->exists()) { - if($projectResult['total_project'] < 10) { + if ($transaction->where([['type_paket', 'Basic'], ['amount', '!=', null]])->exists()) { + if ($projectResult['total_project'] < 10) { $countCreate = true; } - } elseif ($cloneQueryTransaction->where([['type_paket','Free'],['amount',0]])->exists()) { - if($projectResult['total_project'] < 1) { + } elseif ($cloneQueryTransaction->where([['type_paket', 'Free'], ['amount', 0]])->exists()) { + if ($projectResult['total_project'] < 1) { $countCreate = true; } } else { $countCreate = true; } - if($countCreate) { + if ($countCreate) { $result = Project::create($data); if (!$result) { return response()->json(['status' => 'failed', 'message' => 'Failed to add data!', 'code' => 500], 500); } else { $this->createOfficeHours($result['id']); - $dataResultInsert = Project::where([['nama', $data['nama']],['mulai_proyek', $data['mulai_proyek']]])->first(); + $dataResultInsert = Project::where([['nama', $data['nama']], ['mulai_proyek', $data['mulai_proyek']]])->first(); DB::commit(); return response()->json(['status' => 'success', 'message' => 'Data added!', 'data_result' => $dataResultInsert, 'code' => 200], 200); } @@ -77,68 +108,67 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } + } - public function edit($id) - { - if (empty($id) || !is_int((int)$id)) { - return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + 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:: - select( - 'value_proyek', - 'scoupe_of_work', - 'kode_sortname', - 'jumlah_stakeholder', - 'nama', - 'mulai_proyek', - 'akhir_proyek', - 'area_kerja', - 'rencana_biaya', - 'biaya_actual', - 'company', - 'pm_id', - 'type_proyek_id', - 'divisi_id', - 'persentase_progress', - 'keterangan', - 'durasi_proyek', - 'progress_by_worklog', - 'currency_symbol', - 'late_consequence', - 'assumtion', - 'currency_code', - 'currency_name', - 'project_objectives', - 'considered_success_when', - 'potential_risk', - 'testing_environment', - 'budget_health', - 'phase_id', - 'calculation_status', - 'md.name as divisi_name', - 'm_proyek.company_id' - ) - ->leftJoin('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') - ->where('m_proyek.id', $id) - ->first(); - if (!$result) { + $result = Project::select( + 'value_proyek', + 'scoupe_of_work', + 'kode_sortname', + 'jumlah_stakeholder', + 'nama', + 'mulai_proyek', + 'akhir_proyek', + 'area_kerja', + 'rencana_biaya', + 'biaya_actual', + 'company', + 'pm_id', + 'type_proyek_id', + 'divisi_id', + 'persentase_progress', + 'keterangan', + 'durasi_proyek', + 'progress_by_worklog', + 'currency_symbol', + 'late_consequence', + 'assumtion', + 'currency_code', + 'currency_name', + 'project_objectives', + 'considered_success_when', + 'potential_risk', + 'testing_environment', + 'budget_health', + 'phase_id', + 'calculation_status', + 'md.name as divisi_name', + 'm_proyek.company_id' + ) + ->leftJoin('m_divisi as md', 'md.id', '=', 'm_proyek.divisi_id') + ->where('m_proyek.id', $id) + ->first(); + if (!$result) { return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); } else { 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); + 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); + $data = Project::find($id); - if ($data) { + if ($data) { if ($data->update($request->all())) { return response()->json(['status' => 'success', 'message' => 'Data updated!', 'code' => 200], 200); } else { @@ -147,43 +177,43 @@ class ProjectController extends Controller } else { return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); } - } - - 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, $company_id) - { + } + + 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, $company_id) + { DB::beginTransaction(); - $data = Project::find($id); + $data = Project::find($id); $dateNow = Carbon::now(); - if ($data) { + if ($data) { $this->deleteRelative($id, $company_id); if ($data->delete()) { - // if ($data->update(['deleted_at' => $dateNow, 'deleted_by_id' => $this->currentId])) { + // if ($data->update(['deleted_at' => $dateNow, 'deleted_by_id' => $this->currentId])) { DB::commit(); return response()->json(['status' => 'success', 'message' => 'Data deleted!', 'code' => 200], 200); } else { @@ -192,13 +222,13 @@ class ProjectController extends Controller } } else { DB::rollBack(); - return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); } - } + } - private function deleteRelative($project_id, $company_id) - { - DB::transaction(function() use($project_id, $company_id) { + private function deleteRelative($project_id, $company_id) + { + DB::transaction(function () use ($project_id, $company_id) { UserToProyek::where('proyek_id', $project_id)->delete(); UserToActivity::where('proyek_id', $project_id)->delete(); AssignMaterial::where('proyek_id', $project_id)->delete(); @@ -217,19 +247,19 @@ class ProjectController extends Controller RequestMaterial::where('proyek_id', $project_id)->delete(); $this->deleteVersionGantt($project_id, $company_id); $this->deleteDokumenProject($project_id, $company_id); - },5); - } + }, 5); + } - private function deleteVersionGantt($project_id, $company_id) - { - DB::transaction(function() use($project_id, $company_id) { + private function deleteVersionGantt($project_id, $company_id) + { + DB::transaction(function () use ($project_id, $company_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(); $company = Company::find($company_id); - if($company) { + if ($company) { $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); foreach ($dataRa as $ra) { $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); @@ -255,15 +285,15 @@ class ProjectController extends Controller ShowHideColumn::whereIn("version_gantt_id", $vhIds)->delete(); Activity::whereIn("version_gantt_id", $vhIds)->delete(); ReportActivity::whereIn("activity_id", $activityIds)->delete(); - },5); - } + }, 5); + } - private function deleteDokumenProject($project_id, $company_id) - { - DB::transaction(function() use($project_id, $company_id){ - $dataDokumen = DokumenProject::where([['type_dokumen', 'project-document-out-folder'],['ref_id', $project_id]])->get(); + private function deleteDokumenProject($project_id, $company_id) + { + DB::transaction(function () use ($project_id, $company_id) { + $dataDokumen = DokumenProject::where([['type_dokumen', 'project-document-out-folder'], ['ref_id', $project_id]])->get(); $company = Company::find($company_id); - if($company) { + if ($company) { $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); foreach ($dataDokumen as $dokumen) { if (file_exists($destinationPath['pathDocument'] . $dokumen->file)) { @@ -271,7 +301,7 @@ class ProjectController extends Controller } } } - DokumenProject::where([['type_dokumen', 'project-document-out-folder'],['ref_id', $project_id]])->delete(); + DokumenProject::where([['type_dokumen', 'project-document-out-folder'], ['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(); @@ -281,24 +311,24 @@ class ProjectController extends Controller } } DokumenProject::where("type_dokumen", "project-document-in-folder")->whereIn('ref_id', $ref_ids)->delete(); - },5); - } + }, 5); + } - public function search(Request $request) - { - $payload = $request->all(); + 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(); + $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); - } + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); + } - public function list() - { + public function list() + { DB::beginTransaction(); try { $data = Project::select( @@ -383,67 +413,66 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } + } - 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(); + 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) { + if ($data) { return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); } else { return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); } + } + + public function getSCurve(Request $request) + { + $data = MasterFunctionsHelper::getSCurve($request); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } + + // testing + public function calculateSCurvetest(Request $request) + { + $data = MasterFunctionsHelper::calculateSCurve($request->project_id); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } + + public function calculateSCurve(Request $request) + { + $sCurve = Project::select('scurve')->where('id', $request->project_id)->first(); + return response()->json(['status' => 'success', 'code' => 200, 'data' => json_decode($sCurve->scurve)], 200); + } + + public function sCurveCommand(Request $request) + { + Artisan::call('calculate:scurve', [ + 'project_id' => $request->project_id + ]); + // $project = Project::find($request->project_id); - } - - public function getSCurve(Request $request) - { - $data = MasterFunctionsHelper::getSCurve($request); - return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); - } - - // testing - public function calculateSCurvetest(Request $request) - { - $data = MasterFunctionsHelper::calculateSCurve($request->project_id); - return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); - } - - public function calculateSCurve(Request $request) - { - $sCurve = Project::select('scurve')->where('id', $request->project_id)->first(); - return response()->json(['status' => 'success', 'code' => 200, 'data' => json_decode($sCurve->scurve)], 200); - } - - public function sCurveCommand(Request $request) - { - Artisan::call('calculate:scurve', [ - 'project_id' => $request->project_id - ]); - // $project = Project::find($request->project_id); - - // if ($project) { - // dispatch(new ProcessSCurve($project)); - - // return response()->json(['message' => 'S Curve calculation queued']); - // } - - // return response()->json(['message' => 'Project not found'], 404); - } - - public function getLinearSCurve(Request $request) - { - $data = MasterFunctionsHelper::getLinearSCurve($request); - return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); - } - - public static function setSyncDate($activity_id, $activity, $report) - { + // if ($project) { + // dispatch(new ProcessSCurve($project)); + + // return response()->json(['message' => 'S Curve calculation queued']); + // } + + // return response()->json(['message' => 'Project not found'], 404); + } + + public function getLinearSCurve(Request $request) + { + $data = MasterFunctionsHelper::getLinearSCurve($request); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data], 200); + } + + public static function setSyncDate($activity_id, $activity, $report) + { DB::beginTransaction(); try { $status = AssignMaterial::where('activity_id', $activity_id)->first(); @@ -478,10 +507,10 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } + } - public function synchronizeReport($gantt_id) - { + public function synchronizeReport($gantt_id) + { DB::beginTransaction(); try { $activities = Activity::where("version_gantt_id", $gantt_id)->get(); @@ -517,8 +546,8 @@ class ProjectController extends Controller } else if ($reports[$i]['status'] == 'done') { $activity->actual_end = $reports[$i]['max_date']->setTime(23, 59, 59); } - $activity->start_date = $reports[$i]['min_date']; //same early - $activity->end_date = $reports[$i]['max_date']->setTime(23, 59, 59); // same early + $activity->start_date = $reports[$i]['min_date']; //same early + $activity->end_date = $reports[$i]['max_date']->setTime(23, 59, 59); // same early $startDate = new DateTime($activity->start_date); $endDate = new DateTime($activity->end_date); $duration = MasterFunctionsHelper::countDays($activity->version_gantt_id, $startDate, $endDate); @@ -531,74 +560,54 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } - - public function setBaseline($gantt_id) - { - $activities = Activity::where("version_gantt_id", $gantt_id)->get(); - - foreach ($activities as $activity) { - $activity->update([ - "planned_start" => $activity->start_date, - "planned_end" => $activity->end_date, - "early_start" => $activity->start_date, - "early_end" => $activity->end_date, - ]); - } + } + + public function setBaseline($gantt_id) + { + $activities = Activity::where("version_gantt_id", $gantt_id)->get(); + + foreach ($activities as $activity) { + $activity->update([ + "planned_start" => $activity->start_date, + "planned_end" => $activity->end_date, + "early_start" => $activity->start_date, + "early_end" => $activity->end_date, + ]); + } - return response()->json(['status' => 'success', 'message' => 'Set baseline success!', 'code' => 200], 200); - } + return response()->json(['status' => 'success', 'message' => 'Set baseline success!', 'code' => 200], 200); + } public function setBaselineActivity($activity_id, $gantt_id) - { - $activity = Activity::where([["version_gantt_id", $gantt_id],['id',$activity_id]])->first(); + { + $activity = Activity::where([["version_gantt_id", $gantt_id], ['id', $activity_id]])->first(); $activity->update([ "planned_start" => $activity->start_date, "planned_end" => $activity->end_date, "early_start" => $activity->start_date, "early_end" => $activity->end_date, ]); - return response()->json(['status' => 'success', 'message' => 'Set baseline activity success!', 'code' => 200], 200); - } - - public function getInvoiceIntegration(Request $request) - { - DB::beginTransaction(); - try { - $ganttCount = VersionGantt::where('proyek_id', $request->id)->count(); - $search = urlencode($request->search); - if (empty($search)) { - return response()->json(['status' => 'error', 'message' => 'Empty query string!'], 400); - } - $url = str_replace("SEARCH", $search, config('api.adw') . '/project_cost?project_no=SEARCH'); - - $response = MasterFunctionsHelper::curlReq($url); - if (isset($request->gantt_id)) { - $response->data->total_cost = $response->data->total_cost / $ganttCount; - } - DB::commit(); - return response()->json(['status' => 'success', 'data' => $response, 'code' => 200], 200); - } catch (\Throwable $th) { - DB::rollBack(); - } - } - public function getByUser($id) - { - $userProyek = UserToProyek::query() - ->from('assign_hr_to_proyek AS utp') - ->where([['is_customer', true],['user_id', $id]]) - ->leftJoin('m_users', 'utp.user_id', '=', 'm_users.id') - ->leftJoin('m_proyek', 'utp.proyek_id', '=', 'm_proyek.id') - ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') - ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name', 'm_users.name AS join_first_name') - ->get(); - $totalRecord = $userProyek->count(); - - return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); - } - - public function detail(Request $request, $id, $gantt_id = null, $s_curve = null) - { + return response()->json(['status' => 'success', 'message' => 'Set baseline activity success!', 'code' => 200], 200); + } + + + public function getByUser($id) + { + $userProyek = UserToProyek::query() + ->from('assign_hr_to_proyek AS utp') + ->where([['is_customer', true], ['user_id', $id]]) + ->leftJoin('m_users', 'utp.user_id', '=', 'm_users.id') + ->leftJoin('m_proyek', 'utp.proyek_id', '=', 'm_proyek.id') + ->leftJoin('m_type_proyek', 'm_proyek.type_proyek_id', '=', 'm_type_proyek.id') + ->select('m_proyek.*', 'm_type_proyek.name AS join_second_name', 'm_users.name AS join_first_name') + ->get(); + $totalRecord = $userProyek->count(); + + return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); + } + + public function detail(Request $request, $id, $gantt_id = null, $s_curve = null) + { DB::beginTransaction(); try { if (empty($id) || !is_int((int)$id)) { @@ -673,10 +682,10 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } + } - public function getOverdueActivities(Request $request) - { + public function getOverdueActivities(Request $request) + { DB::beginTransaction(); try { $payload = $request->all(); @@ -712,10 +721,10 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } + } - public function getReportDistribution(Request $request) - { + public function getReportDistribution(Request $request) + { DB::beginTransaction(); try { $payload = $request->all(); @@ -750,25 +759,25 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } - - public function getManpower($proyek_id) - { - $manCount = UserToProyek::where('proyek_id', $proyek_id)->count(); - return response()->json(['totalRecord' => $manCount]); - } - - public function getAssignedHR($gantt_id) - { - $results = UserToActivity::select('assign_hr_to_activity.proyek_id', 'assign_hr_to_activity.user_id', 'm_activity.id', 'm_activity.name', 'm_activity.start_date', 'm_activity.end_date') - ->join('m_activity', 'm_activity.id', '=', 'assign_hr_to_activity.activity_id') - ->where('assign_hr_to_activity.version_gantt_id', $gantt_id) - ->get(); - return response()->json(['data' => $results]); - } - - public function dashboard($id) - { + } + + public function getManpower($proyek_id) + { + $manCount = UserToProyek::where('proyek_id', $proyek_id)->count(); + return response()->json(['totalRecord' => $manCount]); + } + + public function getAssignedHR($gantt_id) + { + $results = UserToActivity::select('assign_hr_to_activity.proyek_id', 'assign_hr_to_activity.user_id', 'm_activity.id', 'm_activity.name', 'm_activity.start_date', 'm_activity.end_date') + ->join('m_activity', 'm_activity.id', '=', 'assign_hr_to_activity.activity_id') + ->where('assign_hr_to_activity.version_gantt_id', $gantt_id) + ->get(); + return response()->json(['data' => $results]); + } + + public function dashboard($id) + { DB::beginTransaction(); try { $data = Project::query() @@ -822,23 +831,23 @@ class ProjectController extends Controller } catch (\Throwable $th) { DB::rollBack(); } - } + } - private function httpReq($search) - { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, str_replace("ADDR", $search, API_GEOLOCATION)); + private function httpReq($search) + { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, str_replace("ADDR", $search, API_GEOLOCATION)); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_VERBOSE, true); - curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_VERBOSE, true); + curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); - $info = curl_getinfo($ch); + $info = curl_getinfo($ch); - $output = curl_exec($ch); - curl_close($ch); + $output = curl_exec($ch); + curl_close($ch); - return json_decode($output); - } + return json_decode($output); + } } diff --git a/app/Http/Controllers/RequestMaterialController.php b/app/Http/Controllers/RequestMaterialController.php index 605cf5f..17a47d6 100644 --- a/app/Http/Controllers/RequestMaterialController.php +++ b/app/Http/Controllers/RequestMaterialController.php @@ -8,13 +8,15 @@ use App\Models\MaterialResource; class RequestMaterialController extends Controller { - private function sanitizeDecimal($number) { - $number = str_replace(".","",$number); - $number = str_replace(",",".",$number); + private function sanitizeDecimal($number) + { + $number = str_replace(".", "", $number); + $number = str_replace(",", ".", $number); return $number; } - public function add(Request $request){ + public function add(Request $request) + { $this->validate($request, [ 'proyek_id' => 'required', 'description' => 'required', @@ -32,36 +34,37 @@ class RequestMaterialController extends Controller $result = RequestMaterial::create($data); - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add!','code'=> 500], 500); + 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); + 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); + 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); + if ($result) + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); } public function delete($id) { $data = RequestMaterial::find($id); - if($data) + if ($data) $delete = $data->delete(); - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + 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); + 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); + return response()->json(['status' => 'failed', 'message' => 'Failed to delete!', 'code' => 500], 500); } public function search(Request $request) @@ -72,7 +75,7 @@ class RequestMaterialController extends Controller $countBuilder = $dataBuilder['count']; $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } public function list() @@ -80,35 +83,35 @@ class RequestMaterialController extends Controller $data = RequestMaterial::all(); $countData = $data->count(); - if($data) - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + 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); + 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(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + if (empty($id) || !is_int((int)$id)) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); $reqMaterial = RequestMaterial::find($id); - if(!$reqMaterial) - return response()->json(['status'=>'failed','message'=>'data request material not found!','code'=>400], 400); + 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); + 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); } - if($dataForm['status']=="receipt to warehouse"){ + if ($dataForm['status'] == "receipt to warehouse") { $materialResource = MaterialResource::where('name', 'ilike', $reqMaterial->description)->first(); - if($materialResource){ + 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); + return response()->json(['status' => 'success', 'code' => 200], 200); } $reqMaterial->update($request->all()); @@ -123,79 +126,32 @@ class RequestMaterialController extends Controller "created_by" => $this->currentName ); - if(!MaterialResource::create($preparedMaterialResource )) - return response()->json(['status'=>'failed','message'=>'add data material resource failed!','code'=>400], 400); + 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); + return response()->json(['status' => 'success', 'message' => 'add data material resource successfully!', 'code' => 200], 200); } - if($dataForm['status']=="receipt to site"){ + 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); + 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); + 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); + 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); - } - - private function curlReq($url, $token){ - $ch = curl_init(); - $headers = [ - 'Authorization: '.$token - ]; - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - - $response = curl_exec($ch); - if ($response === false) - $response = curl_error($ch); - curl_close($ch); - - return json_decode($response); - } - - public function getMaterialIntegration(Request $request) { - $search = urlencode($request->name); - if(empty($search)) - return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw').'/stock_master?name=SEARCH'); - $token = config('api.adw_token'); - $firstResponse = $this->curlReq($url, $token); - - if($firstResponse->total == 0) - return response()->json(['status'=>'error', 'message' => 'Data not found!', 'code'=>404], 404); - - $data = $firstResponse->data; - $currentPage = 1; - - if($firstResponse->last_page > 0) { - do { - $currentPage++; - $response = $this->curlReq($url.'&page='.$currentPage, $token); - foreach($response->data as $d){ - array_push($data, $d); - } - } while ($currentPage < 5); - // let the user narrow down the search by themself - // a searching action with 'cable' keyword could take minutes - // because there are >1k items associated with that keyword - } + if (!$reqMaterial->update($request->all())) + return response()->json(['status' => 'failed', 'message' => 'request material failed updated!', 'code' => 400], 400); - return response()->json(['status'=>'success', 'data'=> $data, 'total' => count($data), 'code'=>200], 200); + return response()->json(['status' => 'success', 'message' => 'request material successfully updated!', 'code' => 200], 200); } } diff --git a/app/Http/Controllers/UserToProyekController.php b/app/Http/Controllers/UserToProyekController.php index 7bfab8f..eaadc28 100644 --- a/app/Http/Controllers/UserToProyekController.php +++ b/app/Http/Controllers/UserToProyekController.php @@ -24,114 +24,115 @@ class UserToProyekController extends Controller $result = UserToProyek::create($data); - if($result){ - return response()->json(['status'=>'success','message'=>'assign hr to proyek successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'assign hr to proyek failed!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'message' => 'assign hr to proyek successfully!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'assign hr to proyek failed!', 'code' => 400], 400); } } - public function addMultiple(Request $request){ + public function addMultiple(Request $request) + { $user_IDs = $request->user_id; $data = UserToProyek::where([ - ["proyek_id" , $request->proyek_id], - ['is_customer',true] + ["proyek_id", $request->proyek_id], + ['is_customer', true] ]); - if($data){ + if ($data) { $data->delete(); } - if(is_array($user_IDs) && count($user_IDs) > 0){ + if (is_array($user_IDs) && count($user_IDs) > 0) { $countRes = 0; - foreach($user_IDs as $item){ + foreach ($user_IDs as $item) { $dataInsert = array( "user_id" => $item, "proyek_id" => $request->proyek_id, "created_by" => $this->currentName, - 'is_customer'=>true, - 'project_role'=> $request->project_role + 'is_customer' => true, + 'project_role' => $request->project_role ); $result = UserToProyek::create($dataInsert); - if($result){ + if ($result) { $countRes++; - }else{ + } else { $countRes--; } } - if($countRes > 0){ - return response()->json(['status'=>'success' ,'message'=>'Project customer successfull created','code'=>200]); - }else{ - return response()->json(['status'=>'failed' ,'message'=>'Project customer failed created','code'=>400]); + if ($countRes > 0) { + return response()->json(['status' => 'success', 'message' => 'Project customer successfull created', 'code' => 200]); + } else { + return response()->json(['status' => 'failed', 'message' => 'Project customer failed created', 'code' => 400]); } - }else{ - return response()->json(['status'=>'failed' ,'message'=>'Project customer failed created','code'=>200]); + } else { + return response()->json(['status' => 'failed', 'message' => 'Project customer failed created', 'code' => 200]); } - } - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','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 = UserToProyek::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 hr to proyek, please try again later!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get data assign hr to proyek, 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); + if (!$id || (int) $id < 0 || $id == "") { + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); } $data = UserToProyek::find($id); - if($data){ + if ($data) { $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek not found!','code'=>400], 400); + } else { + return response()->json(['status' => 'failed', 'message' => 'data assign hr to proyek not found!', 'code' => 400], 400); die(); } - if($result){ - return response()->json(['status'=>'success','message'=>'data assign hr to proyek successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek failed updated!','code'=>400], 400); + if ($result) { + return response()->json(['status' => 'success', 'message' => 'data assign hr to proyek successfully updated!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data assign hr to proyek failed updated!', 'code' => 400], 400); } } public function delete($id, $company_id) { $data = UserToProyek::find($id); - if($data){ + if ($data) { $userId = $data->user_id; $proyekId = $data->proyek_id; $delete = $data->delete(); - if($delete){ + if ($delete) { $this->deleteRelative($proyekId, $userId, $company_id); } - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek not found!','code'=>400], 400); + } else { + return response()->json(['status' => 'failed', 'message' => 'data assign hr to proyek not found!', 'code' => 400], 400); die(); } - if($delete){ - return response()->json(['status'=>'success','message'=>'data assign hr to proyek successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek failed deleted!','code'=>400], 400); + if ($delete) { + return response()->json(['status' => 'success', 'message' => 'data assign hr to proyek successfully deleted!', 'code' => 200], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'data assign hr to proyek failed deleted!', 'code' => 400], 400); } } @@ -141,13 +142,13 @@ class UserToProyekController extends Controller foreach ($uta as $value) { $dataRa = ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->get(); $company = Company::find($company_id); - if($company) { + if ($company) { $destinationPath = $this->setCustomeDirectoryUpload($company['company_name']); foreach ($dataRa as $ra) { $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); foreach ($images as $image) { - if(file_exists($destinationPath['pathImage'].$image->image)){ - unlink($destinationPath['pathImage'].$image->image); + if (file_exists($destinationPath['pathImage'] . $image->image)) { + unlink($destinationPath['pathImage'] . $image->image); } } Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); @@ -166,7 +167,7 @@ class UserToProyekController extends Controller $countBuilder = $dataBuilder['count']; $dataGet = $builder->get(); $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataGet, 'totalRecord' => $totalRecord], 200); } public function list() @@ -174,14 +175,15 @@ class UserToProyekController extends Controller $data = UserToProyek::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 assign hr to proyek, please try again later!','code'=>400], 400); + if ($data) { + return response()->json(['status' => 'success', 'code' => 200, 'data' => $data, 'totalRecord' => $countData], 200); + } else { + return response()->json(['status' => 'failed', 'message' => 'failed get list assign hr to proyek, please try again later!', 'code' => 400], 400); } } - public function select(Request $request){ + public function select(Request $request) + { $search = $request->query('search'); @@ -190,73 +192,28 @@ class UserToProyekController extends Controller $include = []; - if($idActivity && $idActivity > 0){ + if ($idActivity && $idActivity > 0) { $dataF = UserToActivity::select("user_id")->where("activity_id", $idActivity)->get(); - foreach($dataF as $val){ + foreach ($dataF as $val) { $include[] = $val->user_id; } } - if($search && !empty($search)){ + if ($search && !empty($search)) { $data = UserToProyek::select("m_users.id as id", "m_users.name as name")->join('m_users', 'm_users.id', '=', 'assign_hr_to_proyek.user_id') - ->where("assign_hr_to_proyek.proyek_id", $idProyek)->where("m_users.name", 'like', '%'.$search.'%')->whereIn("m_users.id", $include)->get(); - }else{ + ->where("assign_hr_to_proyek.proyek_id", $idProyek)->where("m_users.name", 'like', '%' . $search . '%')->whereIn("m_users.id", $include)->get(); + } else { $data = UserToProyek::select("m_users.id as id", "m_users.name as name")->where("assign_hr_to_proyek.proyek_id", $idProyek)->join('m_users', 'm_users.id', '=', 'assign_hr_to_proyek.user_id')->whereIn("m_users.id", $include)->get(); } - if($data instanceof \Illuminate\Database\Eloquent\Collection){ + if ($data instanceof \Illuminate\Database\Eloquent\Collection) { $pm = array( - "id"=>$this->currentId, - "name"=> "Project Manager" + "id" => $this->currentId, + "name" => "Project Manager" ); $data->push($pm); } return response()->json($data); } - - private function curlReq($url, $token){ - $ch = curl_init(); - $headers = [ - 'Authorization: '.$token - ]; - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - - $response = curl_exec($ch); - if ($response === false) - $response = curl_error($ch); - curl_close($ch); - - return json_decode($response); - } - - public function getEmployeeIntegration(Request $request) { - $search = urlencode($request->name); - if(empty($search)) - return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw').'/employees?emp_name=SEARCH'); - $token = config('api.adw_token'); - $firstResponse = $this->curlReq($url, $token); - - if($firstResponse->total == 0) - return response()->json(['status'=>'error', 'message' => 'Data not found!', 'code'=>404], 404); - - $data = $firstResponse->data; - return response()->json([$data]); - $currentPage = 1; - - if($firstResponse->last_page > 0) { - do { - $currentPage++; - $response = $this->curlReq($url.'&page='.$currentPage, $token); - foreach($response->data as $d){ - array_push($data, $d); - } - } while ($currentPage < $firstResponse->last_page); - } - - return response()->json(['status'=>'success', 'data'=> $data, 'total' => count($data), 'code'=>200], 200); - } }