diff --git a/app/Helpers/MasterFunctionsHelper.php b/app/Helpers/MasterFunctionsHelper.php index 5c9764f..706d734 100644 --- a/app/Helpers/MasterFunctionsHelper.php +++ b/app/Helpers/MasterFunctionsHelper.php @@ -1,981 +1,981 @@ -max("id"); - if (!$maxGanttId) { - $data = array( - "proyek_id" => $id - ); - } else { - $data = array( - "last_gantt_id" => $maxGanttId, - "proyek_id" => $id - ); - } - return $data; - } - - // dipake di dashboard project & bod - public function getSCurve($request) - { - $allGantt = []; - if (!is_int($request)) { - $dataPayload = $request->all(); - if (isset($dataPayload['gantt_id'])) { - $allGantt[] = $dataPayload['gantt_id']; - } else { - $allGantt[] = MasterFunctionsHelper::getLatestGantt($dataPayload['project_id']); - } - } else { - $allGantt[] = MasterFunctionsHelper::getLatestGantt($request); - } - foreach ($allGantt as $gantt) { - if (!isset($gantt['last_gantt_id'])) { - $ganttId = $gantt; - } else { - $ganttId = $gantt['last_gantt_id']; - } - $gantt = VersionGantt::find($ganttId)->toArray(); - // foreach ($gantt as $key => $value) { - // Log::info('gantt '.$value.' index '.$key); - // } - if (isset($gantt['calculation_type'])) { - if ($gantt['calculation_type'] == 'simple') { - // to do - return MasterFunctionsHelper::calculateProgressBasedOnSimple($gantt); - } else { - return MasterFunctionsHelper::calculateProgressBasedOnReportMaterial($gantt); - } - } - } - } - - public function getLinearSCurve($request) - { - $ftths = HierarchyFtth::where('project_id', $request->project_id)->get(); - $ttlProgress = 0; - $ttlPlanning = 0; - - foreach ($ftths as $ftth) { - $progress = VersionGantt::where('hierarchy_ftth_id', $ftth->id)->sum('progress'); - $planning = VersionGantt::where('hierarchy_ftth_id', $ftth->id)->sum('bobot'); - $ttlProgress += $progress; - $ttlPlanning += $planning; - } - - $minDate = Project::select('mulai_proyek')->where('id', $request->project_id)->first(); - $maxDate = Project::select('akhir_proyek')->where('id', $request->project_id)->first(); - - $begin = new \DateTime($minDate->mulai_proyek . ' Monday'); - - $end = new \DateTime($maxDate->akhir_proyek . ' Friday'); - - $interval = new \DateInterval('P7D'); - - $period = new \DatePeriod($begin, $interval, $end); - $dates = iterator_to_array($period); - $count = count($dates); - - $avgProgress = $ttlProgress / $ttlPlanning / $count * 100; - $avgPlanning = $ttlPlanning / $ttlPlanning / $count * 100; - $progressData = []; - $planningData = []; - $dates = []; - $tempProgress = 0; - $tempPlanning = 0; - array_push($progressData, round($tempProgress, 2)); - array_push($planningData, round($tempPlanning, 2)); - foreach ($period as $p) { - $tempProgress += $avgProgress; - $tempPlanning += $avgPlanning; - array_push($progressData, round($tempProgress, 2)); - array_push($planningData, round($tempPlanning, 2)); - array_push($dates, $p->format("Y-m-d")); - } - - $dataResponse = array( - "percentagePlan" => $planningData, - "percentageReal" => $progressData, - "date" => $dates, - ); - - $dataFinal[] = array( - "data" => $dataResponse, - ); - 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 . ' Monday'); - $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'); - $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'); - $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 += $keyPlanM->bobot_planning; - 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->biaya_actual / $keyActualM->duration; - } 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; - - // if($tempTtlPercentPlan >= 100 || $tempTtlPercentActual >= $keyGantt['progress'];){ - // if($tempTtlPercentActual >= 100) - // $tempTtlPercentActual = 100; - // if($tempTtlPercentPlan >= 100) - // $tempTtlPercentPlan = 100; - - // if($tempTtlPercentActual >= $keyGantt['progress']) - // $tempTtlPercentActual = $keyGantt['progress']; - 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]; - $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 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"); - } - - $alreadyHasReport = DB::table('report_activity_material as a') - ->select('a.id') - ->join('m_activity as b', 'b.id', '=', 'a.activity_id') - ->exists(); - - $minDate = $dataProject->mulai_proyek; - - $begin = new \DateTime($minDate); - $begin->modify('last Monday'); - if (isset($dataPayload['end_date'])) { - $maxDate = $dataPayload['end_date']; - $end = new \DateTime($maxDate); - $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 { - // $maxDate = DB::table('assign_material_to_activity as ama') - // ->where("ama.proyek_id", $projectId) - // ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') - // ->max("plan_date"); // plan date overlapped with assign_material_to_activity's, it should be m_activity's - $maxDate = $dataProject->akhir_proyek; - $end = new \DateTime($maxDate); - $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"); - // $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) - ->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) - ->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.proyek_id', '=', $projectId) - ->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) { - $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) - ->unionAll(function ($query) { - $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); - })->orderBy('id', 'asc'); - }, 'subquery') - ->sum('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 += $keyPlanM->bobot_planning; - 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(); - if (!isset($sumVolActual)) { - $sumVolActual = (object) [ - 'activity_id' => $keyActualM->activity_id, - 'ttl_qty_plan' => "0" - ]; - } - $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(); - if (!isset($checkStatusActivity)) { - $checkStatusActivity = (object) [ - 'activity_id' => $keyActualM->activity_id, - 'status_activity' => 'open' - ]; - } - if ($sumVolActual->ttl_qty_plan == "0") { - $actual = 0; - } else { - $actual = $keyActualM->qty / $sumVolActual->ttl_qty_plan; - } - $dataTempReport[$w]['percentage'] = $actual * $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 ( $actual >= 1 || (int) $sumVolActual->ttl_qty_plan == (int) $sumReportActual) { - $sumPercentageActual += ($actual * $keyActualM->bobot_planning) * (95 / 100); - // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; - } else { - $sumPercentageActual += $actual * $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->biaya_actual / $keyActualM->duration; - } 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); - } else { - $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); - $tempPercentagePlan[] = round($sumPercentagePlan, 2); - $tempPercentageReal[] = round($sumPercentageActual, 2); - } - $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; - $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, - ); - - return $dataFinal; - } - - public function calculateProgressBasedOnSimple($keyGantt) - { - DB::enableQueryLog(); - - $dataFinal = []; - $dataPayload = []; - $dataPayload['period'] = 'week'; - - $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(); - - // if(!$alreadyHasReport) - // return $dataFinal; - - $minDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('start_date')->first(); - - $begin = new \DateTime($minDate . ' Monday'); - if (isset($dataPayload['end_date'])) { - $maxDate = $dataPayload['end_date']; - $end = new \DateTime($maxDate); - /* $interval = \DateInterval::createFromDateString('1 day'); */// should be using this but its bugged - $interval = new \DateInterval('P7D'); - } else { - // $maxDate = 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("plan_date"); // plan date overlapped with assign_material_to_activity's, it should be m_activity's - $maxDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('end_date')->first(); - $end = new \DateTime($maxDate . ' 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"); - - $dataPlanM = DB::table('m_activity') - ->select('id as activity_id', 'bobot_planning', 'start_date', 'biaya_actual', 'duration', 'persentase_progress') - // ->join('m_activity as a', 'a.id', '=', 'activity_id') - ->where('proyek_id', '=', $keyGantt['proyek_id']) - ->where('type_activity', '=', 'task') - ->where('version_gantt_id', '=', $keyGantt['id']) - ->whereDate('start_date', '<=', $dt->format("Y-m-d")) - ->whereDate('start_date', '>', $minSevenDays) - ->get(); - - $dataActualM = DB::table('m_activity as a') - ->select('mapl.id as id_progress_log', 'mapl.activity_id', 'mapl.variance', 'mapl.created_at', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') - ->join('m_activity_progress_log as mapl', 'a.id', '=', 'mapl.activity_id') - ->where('a.version_gantt_id', '=', $keyGantt['id']) - ->where('a.type_activity', '=', 'task') - ->where('mapl.variance', '>', 0) - ->where('a.proyek_id', '=', $keyGantt['proyek_id']) - ->whereDate('mapl.created_at', '<=', $dt->format("Y-m-d")) - ->whereDate('mapl.created_at', '>', $minSevenDays) - ->get(); - $dataTempPlan = []; - $x = 0; - $sumPercentagePlan = 0; - $totalACWP = isset($totalACWP) ? $totalACWP : 0; - $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; - - foreach ($dataPlanM as $keyPlanM) { - - $dataTempPlan[$x]['activity_id'] = $keyPlanM->activity_id; - $dataTempPlan[$x]['qty_plan'] = $keyPlanM->bobot_planning; - $dataTempPlan[$x]['plan_date'] = $keyPlanM->start_date; - $dataTempPlan[$x]['start_activity'] = $keyPlanM->start_date; - $dataTempPlan[$x]['bobot_planning'] = $keyPlanM->bobot_planning; - $dataTempPlan[$x]['ttl_plan'] = $keyPlanM->bobot_planning; - $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 += $keyPlanM->bobot_planning; - $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('m_activity_progress_log') - ->select('id', DB::raw('SUM(variance) as ttl_percen_act')) - ->where('id', '=', $keyActualM->id_progress_log) - ->groupBy('id') - ->first(); - $dataTempReport[$w]['id_progress_log'] = $keyActualM->id_progress_log; - // $dataTempReport [$w]['qty'] = $keyActualM->qty; - $dataTempReport[$w]['report_date'] = $keyActualM->created_at; - $dataTempReport[$w]['bobot_planning'] = $keyActualM->bobot_planning; - // $dataTempReport [$w]['ttl_plan'] = $sumVolActual->ttl_percen_act ? $sumVolActual->ttl_percen_act : 0; - $dataTempReport[$w]['biaya_actual'] = $keyActualM->biaya_actual; - $dataTempReport[$w]['duration'] = $keyActualM->duration; - $dataTempReport[$w]['persentase_progress'] = $keyActualM->persentase_progress; - try { - $dataTempReport[$w]['percentage'] = $sumVolActual->ttl_percen_act ? ($sumVolActual->ttl_percen_act / 100) * $keyActualM->bobot_planning : 0; - $sumPercentageActual += $sumVolActual->ttl_percen_act ? ($sumVolActual->ttl_percen_act / 100) * $keyActualM->bobot_planning : 0; - $totalACWP += $keyActualM->biaya_actual / $keyActualM->duration; - } 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; - - if ($tempTtlPercentPlan >= 100 || $tempTtlPercentActual >= 100) { - if ($tempTtlPercentActual >= 100) - $tempTtlPercentActual = 100; - if ($tempTtlPercentPlan >= 100) - $tempTtlPercentPlan = 100; - } - - $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); - } - $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, - 'gantt' => $keyGantt, - ]); - } - $estimatedCost = $totalACWP > $totalRencanaBudget ? $totalACWP : $totalRencanaBudget; - - $costDeviation = $totalRencanaBudget - $estimatedCost; - if ($costDeviation > 0) { - $potential = "SAVING"; - } else { - $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; - } - - $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; - } - -} \ No newline at end of file +max("id"); + if (!$maxGanttId) { + $data = array( + "proyek_id" => $id + ); + } else { + $data = array( + "last_gantt_id" => $maxGanttId, + "proyek_id" => $id + ); + } + return $data; + } + + // dipake di dashboard project & bod + public function getSCurve($request) + { + $allGantt = []; + if (!is_int($request)) { + $dataPayload = $request->all(); + if (isset($dataPayload['gantt_id'])) { + $allGantt[] = $dataPayload['gantt_id']; + } else { + $allGantt[] = MasterFunctionsHelper::getLatestGantt($dataPayload['project_id']); + } + } else { + $allGantt[] = MasterFunctionsHelper::getLatestGantt($request); + } + foreach ($allGantt as $gantt) { + if (!isset($gantt['last_gantt_id'])) { + $ganttId = $gantt; + } else { + $ganttId = $gantt['last_gantt_id']; + } + $gantt = VersionGantt::find($ganttId)->toArray(); + // foreach ($gantt as $key => $value) { + // Log::info('gantt '.$value.' index '.$key); + // } + if (isset($gantt['calculation_type'])) { + if ($gantt['calculation_type'] == 'simple') { + // to do + return MasterFunctionsHelper::calculateProgressBasedOnSimple($gantt); + } else { + return MasterFunctionsHelper::calculateProgressBasedOnReportMaterial($gantt); + } + } + } + } + + public function getLinearSCurve($request) + { + $ftths = HierarchyFtth::where('project_id', $request->project_id)->get(); + $ttlProgress = 0; + $ttlPlanning = 0; + + foreach ($ftths as $ftth) { + $progress = VersionGantt::where('hierarchy_ftth_id', $ftth->id)->sum('progress'); + $planning = VersionGantt::where('hierarchy_ftth_id', $ftth->id)->sum('bobot'); + $ttlProgress += $progress; + $ttlPlanning += $planning; + } + + $minDate = Project::select('mulai_proyek')->where('id', $request->project_id)->first(); + $maxDate = Project::select('akhir_proyek')->where('id', $request->project_id)->first(); + + $begin = new \DateTime($minDate->mulai_proyek . ' Monday'); + + $end = new \DateTime($maxDate->akhir_proyek . ' Friday'); + + $interval = new \DateInterval('P7D'); + + $period = new \DatePeriod($begin, $interval, $end); + $dates = iterator_to_array($period); + $count = count($dates); + + $avgProgress = $ttlProgress / $ttlPlanning / $count * 100; + $avgPlanning = $ttlPlanning / $ttlPlanning / $count * 100; + $progressData = []; + $planningData = []; + $dates = []; + $tempProgress = 0; + $tempPlanning = 0; + array_push($progressData, round($tempProgress, 2)); + array_push($planningData, round($tempPlanning, 2)); + foreach ($period as $p) { + $tempProgress += $avgProgress; + $tempPlanning += $avgPlanning; + array_push($progressData, round($tempProgress, 2)); + array_push($planningData, round($tempPlanning, 2)); + array_push($dates, $p->format("Y-m-d")); + } + + $dataResponse = array( + "percentagePlan" => $planningData, + "percentageReal" => $progressData, + "date" => $dates, + ); + + $dataFinal[] = array( + "data" => $dataResponse, + ); + 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 . ' Monday'); + $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'); + $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'); + $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 += $keyPlanM->bobot_planning; + 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->biaya_actual / $keyActualM->duration; + } 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; + + // if($tempTtlPercentPlan >= 100 || $tempTtlPercentActual >= $keyGantt['progress'];){ + // if($tempTtlPercentActual >= 100) + // $tempTtlPercentActual = 100; + // if($tempTtlPercentPlan >= 100) + // $tempTtlPercentPlan = 100; + + // if($tempTtlPercentActual >= $keyGantt['progress']) + // $tempTtlPercentActual = $keyGantt['progress']; + 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]; + $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 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"); + } + + $alreadyHasReport = DB::table('report_activity_material as a') + ->select('a.id') + ->join('m_activity as b', 'b.id', '=', 'a.activity_id') + ->exists(); + + $minDate = $dataProject->mulai_proyek; + + $begin = new \DateTime($minDate); + $begin->modify('last Monday'); + if (isset($dataPayload['end_date'])) { + $maxDate = $dataPayload['end_date']; + $end = new \DateTime($maxDate); + $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 { + // $maxDate = DB::table('assign_material_to_activity as ama') + // ->where("ama.proyek_id", $projectId) + // ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') + // ->max("plan_date"); // plan date overlapped with assign_material_to_activity's, it should be m_activity's + $maxDate = $dataProject->akhir_proyek; + $end = new \DateTime($maxDate); + $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"); + // $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) + ->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) + ->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.proyek_id', '=', $projectId) + ->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) { + $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) + ->unionAll(function ($query) { + $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); + })->orderBy('id', 'asc'); + }, 'subquery') + ->sum('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 += $keyPlanM->bobot_planning; + 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(); + if (!isset($sumVolActual)) { + $sumVolActual = (object) [ + 'activity_id' => $keyActualM->activity_id, + 'ttl_qty_plan' => "0" + ]; + } + $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(); + if (!isset($checkStatusActivity)) { + $checkStatusActivity = (object) [ + 'activity_id' => $keyActualM->activity_id, + 'status_activity' => 'open' + ]; + } + if ($sumVolActual->ttl_qty_plan == "0") { + $actual = 0; + } else { + $actual = $keyActualM->qty / $sumVolActual->ttl_qty_plan; + } + $dataTempReport[$w]['percentage'] = $actual * $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 ( $actual >= 1 || (int) $sumVolActual->ttl_qty_plan == (int) $sumReportActual) { + $sumPercentageActual += ($actual * $keyActualM->bobot_planning) * (95 / 100); + // $sumPercentageActual = $sumPercentageActual > $keyGantt['progress'] ? $keyGantt['progress'] : $sumPercentageActual; + } else { + $sumPercentageActual += $actual * $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->biaya_actual / $keyActualM->duration; + } 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); + } else { + $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); + $tempPercentagePlan[] = round($sumPercentagePlan, 2); + $tempPercentageReal[] = round($sumPercentageActual, 2); + } + $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; + $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, + ); + + return $dataFinal; + } + + public function calculateProgressBasedOnSimple($keyGantt) + { + DB::enableQueryLog(); + + $dataFinal = []; + $dataPayload = []; + $dataPayload['period'] = 'week'; + + $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(); + + // if(!$alreadyHasReport) + // return $dataFinal; + + $minDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('start_date')->first(); + + $begin = new \DateTime($minDate . ' Monday'); + if (isset($dataPayload['end_date'])) { + $maxDate = $dataPayload['end_date']; + $end = new \DateTime($maxDate); + /* $interval = \DateInterval::createFromDateString('1 day'); */// should be using this but its bugged + $interval = new \DateInterval('P7D'); + } else { + // $maxDate = 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("plan_date"); // plan date overlapped with assign_material_to_activity's, it should be m_activity's + $maxDate = Activity::where('version_gantt_id', $keyGantt['id'])->whereNull('parent_id')->pluck('end_date')->first(); + $end = new \DateTime($maxDate . ' 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"); + + $dataPlanM = DB::table('m_activity') + ->select('id as activity_id', 'bobot_planning', 'start_date', 'biaya_actual', 'duration', 'persentase_progress') + // ->join('m_activity as a', 'a.id', '=', 'activity_id') + ->where('proyek_id', '=', $keyGantt['proyek_id']) + ->where('type_activity', '=', 'task') + ->where('version_gantt_id', '=', $keyGantt['id']) + ->whereDate('start_date', '<=', $dt->format("Y-m-d")) + ->whereDate('start_date', '>', $minSevenDays) + ->get(); + + $dataActualM = DB::table('m_activity as a') + ->select('mapl.id as id_progress_log', 'mapl.activity_id', 'mapl.variance', 'mapl.created_at', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') + ->join('m_activity_progress_log as mapl', 'a.id', '=', 'mapl.activity_id') + ->where('a.version_gantt_id', '=', $keyGantt['id']) + ->where('a.type_activity', '=', 'task') + ->where('mapl.variance', '>', 0) + ->where('a.proyek_id', '=', $keyGantt['proyek_id']) + ->whereDate('mapl.created_at', '<=', $dt->format("Y-m-d")) + ->whereDate('mapl.created_at', '>', $minSevenDays) + ->get(); + $dataTempPlan = []; + $x = 0; + $sumPercentagePlan = 0; + $totalACWP = isset($totalACWP) ? $totalACWP : 0; + $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; + + foreach ($dataPlanM as $keyPlanM) { + + $dataTempPlan[$x]['activity_id'] = $keyPlanM->activity_id; + $dataTempPlan[$x]['qty_plan'] = $keyPlanM->bobot_planning; + $dataTempPlan[$x]['plan_date'] = $keyPlanM->start_date; + $dataTempPlan[$x]['start_activity'] = $keyPlanM->start_date; + $dataTempPlan[$x]['bobot_planning'] = $keyPlanM->bobot_planning; + $dataTempPlan[$x]['ttl_plan'] = $keyPlanM->bobot_planning; + $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 += $keyPlanM->bobot_planning; + $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('m_activity_progress_log') + ->select('id', DB::raw('SUM(variance) as ttl_percen_act')) + ->where('id', '=', $keyActualM->id_progress_log) + ->groupBy('id') + ->first(); + $dataTempReport[$w]['id_progress_log'] = $keyActualM->id_progress_log; + // $dataTempReport [$w]['qty'] = $keyActualM->qty; + $dataTempReport[$w]['report_date'] = $keyActualM->created_at; + $dataTempReport[$w]['bobot_planning'] = $keyActualM->bobot_planning; + // $dataTempReport [$w]['ttl_plan'] = $sumVolActual->ttl_percen_act ? $sumVolActual->ttl_percen_act : 0; + $dataTempReport[$w]['biaya_actual'] = $keyActualM->biaya_actual; + $dataTempReport[$w]['duration'] = $keyActualM->duration; + $dataTempReport[$w]['persentase_progress'] = $keyActualM->persentase_progress; + try { + $dataTempReport[$w]['percentage'] = $sumVolActual->ttl_percen_act ? ($sumVolActual->ttl_percen_act / 100) * $keyActualM->bobot_planning : 0; + $sumPercentageActual += $sumVolActual->ttl_percen_act ? ($sumVolActual->ttl_percen_act / 100) * $keyActualM->bobot_planning : 0; + $totalACWP += $keyActualM->biaya_actual / $keyActualM->duration; + } 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; + + if ($tempTtlPercentPlan >= 100 || $tempTtlPercentActual >= 100) { + if ($tempTtlPercentActual >= 100) + $tempTtlPercentActual = 100; + if ($tempTtlPercentPlan >= 100) + $tempTtlPercentPlan = 100; + } + + $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); + } + $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, + 'gantt' => $keyGantt, + ]); + } + $estimatedCost = $totalACWP > $totalRencanaBudget ? $totalACWP : $totalRencanaBudget; + + $costDeviation = $totalRencanaBudget - $estimatedCost; + if ($costDeviation > 0) { + $potential = "SAVING"; + } else { + $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; + } + + $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; + } + +} diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index 03990d9..b8af8d4 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -1,913 +1,913 @@ -where("version_gantt_id", $id)->count() == 0) { - if (!$gantt->hierarchy_ftth_id) { - $this->cloneTemplate($id, $proyek_id); - } else { - $this->cloneTemplate($id, $proyek_id, $gantt->hierarchy_ftth_id); - } - } - - $dataGantt = $this->getDataActivity($id); - - return response()->json(['status' => 'success', 'data' => $dataGantt, 'code' => 200], 200); - } - - private function getDataActivity($id) - { - $checkHeader = Activity::where('version_gantt_id', $id)->where('type_activity', 'header')->count(); - $finalData = []; - if ($checkHeader > 0) { - $dataHeader = Activity::where('version_gantt_id', $id)->where('type_activity', 'header')->first(); - $startDate = date_create($dataHeader->start_date); - $endDate = date_create($dataHeader->end_date); - $dataHeader->start_date = date_format($startDate, "Y-m-d H:i:s"); - $dataHeader->end_date = date_format($endDate, "Y-m-d H:i:s"); - $dataHeader->progress = $dataHeader->persentase_progress / 100; - $dataHeader->planned_start = isset($dataHeader->planned_start) ? date_format(date_create($dataHeader->planned_start), "Y-m-d H:i:s") : NULL; - $dataHeader->planned_end = isset($dataHeader->planned_end) ? date_format(date_create($dataHeader->planned_end), "Y-m-d H:i:s") : NULL; - - $actualStart = $this->getFirstLastDateActivity($dataHeader->id, "start"); - $dataHeader->actual_start = date_format(date_create($actualStart), "Y-m-d"); - $actualEnd = $this->getFirstLastDateActivity($dataHeader->id, "end"); - $dataHeader->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "Y-m-d") : NULL; - - $dataHeader->type = "header"; - $dataHeader->text = $dataHeader->name; - $finalData[] = $dataHeader; - $data = Activity::where('version_gantt_id', $id)->where('parent_id', $dataHeader->id)->orderBy('sortorder', 'asc')->get(); - } else { - $data = Activity::where('version_gantt_id', $id)->whereNull('parent_id')->orderBy('sortorder', 'asc')->get(); - } - - foreach ($data as $objRow) { - $type = "project"; - $dataChildren = $this->getChildren($id, $objRow->id); - $startDate = date_create($objRow->start_date); - $endDate = date_create($objRow->end_date); - - if ($objRow->type_activity == "milestone") - $type = $objRow->type_activity; - if (empty($dataChildren)) - $type = "task"; - - $objRow->text = $objRow->name; - $objRow->parent = $objRow->parent_id ? $objRow->parent_id : null; - $objRow->start_date = date_format($startDate, "Y-m-d H:i:s"); - $objRow->end_date = date_format($endDate, "Y-m-d H:i:s"); - $objRow->planned_start = isset($objRow->planned_start) ? date_format(date_create($objRow->planned_start), "Y-m-d H:i:s") : NULL; - $objRow->planned_end = isset($objRow->planned_end) ? date_format(date_create($objRow->planned_end), "Y-m-d H:i:s") : NULL; - - $actualStart = $this->getFirstLastDateActivity($objRow->id, "start"); - $objRow->actual_start = isset($actualStart) ? date_format(date_create($actualStart), "Y-m-d") : NULL; - $actualEnd = $this->getFirstLastDateActivity($objRow->id, "end"); - $objRow->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "Y-m-d") : NULL; - - $objRow->progress = $objRow->persentase_progress / 100; - $objRow->type = $type; - $finalData[] = $objRow; - $finalData = array_merge($finalData, $dataChildren); - } - - $dataLink = Link::where('version_gantt_id', $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 $resultData; - } - - private function getChildren($gantt_id, $parent_id) - { - $finalData = []; - $data = Activity::where('version_gantt_id', $gantt_id)->where('parent_id', $parent_id)->orderBy('sortorder', 'asc')->get(); - foreach ($data as $objRow) { - $objRow->parent = $parent_id; - $objRow->text = $objRow->name; - $objRow->progress = (float) $objRow->persentase_progress / 100; - $startDate = date_create($objRow->start_date); - $endDate = date_create($objRow->end_date); - $objRow->start_date = date_format($startDate, "Y-m-d H:i:s"); - $objRow->end_date = date_format($endDate, "Y-m-d H:i:s"); - $objRow->planned_start = isset($objRow->planned_start) ? date_format(date_create($objRow->planned_start), "Y-m-d H:i:s") : NULL; - $objRow->planned_end = isset($objRow->planned_end) ? date_format(date_create($objRow->planned_end), "Y-m-d H:i:s") : NULL; - - $dataChildren = $this->getChildren($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), "Y-m-d") : NULL; - } elseif (empty($dataChildren)) { - $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)){ - $objRow->auto_scheduling = false; - } - } else { - $objRow->type = "project"; - $actualStart = $this->getFirstLastDateActivity($objRow->id, "start"); - $objRow->actual_start = isset($actualStart) ? date_format(date_create($actualStart), "Y-m-d") : NULL; - - $actualEnd = $this->getFirstLastDateActivity($objRow->id, "end"); - $objRow->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "Y-m-d") : NULL; - } - $finalData[] = $objRow; - $finalData = array_merge($finalData, $dataChildren); - } - return $finalData; - } - - 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"){ - // Log::info("activity ", [$activity]); - return $activity->actual_start; - }else{ - return $this->getActivityFirst($activity->id); - } - - } - - public function getFirstLastDateActivity($id, $params){ - if($params == "start"){ - $data = Activity::select('id', 'parent_id', 'name', 'actual_start')->where('parent_id', $id)->get(); - }else{ - $data = Activity::select('id', 'parent_id', 'name', 'actual_end')->where('parent_id', $id)->get(); - } - $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) { - return isset($item['actual_start']); - }), 'actual_start'); - - $returnActualStartOrEnd = count($actualStartValues) > 0 ? min($actualStartValues) : null; - }else{ - $actualEndValues = array_column(array_filter($dataFinal, function($item) { - return isset($item['actual_end']); - }), 'actual_end'); - - $returnActualStartOrEnd = count($actualEndValues) > 0 ? max($actualEndValues) : null; - } - - // return json_encode(["min"=>$minActualStart, "max"=>$maxActualStart]); - return $returnActualStartOrEnd; - } - - public function getchildActivityForActual($parent, $params){ - if($params == "start"){ - $activity = Activity::select('id', 'actual_start')->where('parent_id', $parent)->get(); - }else{ - $activity = Activity::select('id', 'actual_end')->where('parent_id', $parent)->get(); - } - $temp = []; - foreach($activity as $val1){ - $getChild = $this->getchildActivityForActual($val1->id, $params); - $temp[] = $val1; - $temp = array_merge($temp, $getChild); - } - return $temp; - } - - 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"){ - // Log::info("activity ", [$activity]); - return $activity->actual_end; - }else{ - return $this->getActivityLast($activity->id); - } - - } - - private function cloneTemplate($id, $proyek_id, $hierarchy_ftth_id = null) - { - $project = Project::find($proyek_id); - if ($hierarchy_ftth_id) { - $gantt = VersionGantt::find($id); - $rootActivity = Activity::create([ - 'version_gantt_id' => $id, - 'proyek_id' => $proyek_id, - 'name' => $gantt->name_version, - 'start_date' => $project->mulai_proyek, - 'end_date' => $project->akhir_proyek, - 'rencana_biaya' => $project->rencana_biaya, - 'type_activity' => 'project', - 'created_by' => $this->currentName, - 'sortorder' => 1 - ]); - } else { - $rootActivity = Activity::create([ - 'version_gantt_id' => $id, - 'proyek_id' => $proyek_id, - 'name' => $project->nama, - 'kode_sortname' => $project->kode_sortname, - 'start_date' => $project->mulai_proyek, - 'end_date' => $project->akhir_proyek, - 'rencana_biaya' => $project->rencana_biaya, - 'type_activity' => 'project', - 'created_by' => $this->currentName, - 'sortorder' => 1 - ]); - } - - $resultTypeProject = TemplateGantt::where('proyek_type_id', $project->type_proyek_id) - ->whereNull('parent_id') - ->orderByRaw('id ASC') - ->get(); - - foreach ($resultTypeProject as $objRow) { - $childActivities = TemplateGantt::where("parent_id", $objRow->id)->count(); - $max = Activity::where('version_gantt_id', $id)->max('sortorder'); - $resultNew = Activity::create([ - 'type_activity' => $childActivities > 0 ? "project" : "task", - 'version_gantt_id' => $id, - 'parent_id' => $rootActivity->id, - 'proyek_id' => $proyek_id, - 'name' => $objRow->name_activity, - 'start_date' => date("Y-m-d H:i:s"), - 'end_date' => date("Y-m-d H:i:s"), - 'created_by' => $this->currentName, - 'sortorder' => $max + 1 - ]); - $this->getChildrenTemplate($id, $objRow->id, $project->type_project_id, $proyek_id, $resultNew->id, $project->mulai_proyek); - } - } - - private function getChildrenTemplate($id, $parent_id, $type_proyek_id, $proyek_id, $parent_new, $firstDay) - { - $data = TemplateGantt::where('parent_id', $parent_id)->orderByRaw('id ASC')->get(); - foreach ($data as $objRow) { - $childActivities = TemplateGantt::where("parent_id", $objRow->id)->count(); - $max = Activity::where('version_gantt_id', $id)->max('sortorder'); - $resultNew = Activity::create([ - 'type_activity' => $childActivities > 0 ? "project" : "task", - 'version_gantt_id' => $id, - 'parent_id' => $parent_new, - 'proyek_id' => $proyek_id, - 'name' => $objRow->name_activity, - 'start_date' => $firstDay, - 'end_date' => $firstDay, - 'created_by' => $this->currentName, - 'sortorder' => $max + 1 - ]); - $this->getChildrenTemplate($id, $objRow->id, $type_proyek_id, $proyek_id, $resultNew->id, $firstDay); - } - } - - public function add(Request $request) - { - $this->validate($request, [ - 'version_gantt_id' => 'required' - ]); - - $data = $request->all(); - $data['name'] = $request->text; - $data['persentase_progress'] = $request->progress; - $data['created_by'] = $this->currentName; - $max = Activity::where('version_gantt_id', $request->version_gantt_id)->max('sortorder'); - $data['sortorder'] = $max + 1; - if (!isset($data['type_activity'])) { - $data['type_activity'] = "task"; - } - - $parent = $data['parent_id'] ?? null; - if ($parent) { - $parentData = Activity::find($parent); - if ($parentData->parent_id) { - $parentData->update(["type_activity" => "project"]); - } - CommentActivity::where('activity_id', $parent)->delete(); - UserToActivity::where('activity_id', $parent)->delete(); - } - - if (!$result = Activity::create($data)) - return response()->json(['status' => 'failed', 'action' => 'error', 'code' => 500], 500); - - return response()->json(['status' => 'success', 'action' => 'inserted', 'tid' => $result->id, '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); - - if (!$result = Activity::find($id)) - return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - - return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); - } - - public function update(Request $request, $id) - { - if (empty($id) || !is_int((int) $id)) - return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'id is required!', 'code' => 400], 400); - - $updateBobot = true; - if (!$data = Activity::find($id)) - return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 404], 404); - $dataUpdate = $request->all(); - - $dataUpdate['name'] = $request->text; - $dataUpdate['persentase_progress'] = $request->progress * 100; - $dataUpdate['updated_by'] = $this->currentName; - unset($dataUpdate['sortorder']); - if ($data->type_activity != 'header') - $dataUpdate['type_activity'] = $request->type; - - if ($request->has("target")) { - $this->updateOrder($id, $request->target); - } - - if (!$data->update($dataUpdate)) - return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'data activity failed updated!', 'code' => 400], 400); - - return response()->json(['status' => 'success', 'update_bobot' => $updateBobot, 'data' => $dataUpdate, 'action' => 'updated', 'message' => 'Activity updated!', 'code' => 200], 200); - } - - private function updateOrder($taskId, $target) - { - $nextTask = false; - $targetId = $target; - - if (strpos($target, "next:") === 0) { - $targetId = substr($target, strlen("next:")); - $nextTask = true; - } - - if ($targetId == "null") - return; - - $targetOrder = Activity::find($targetId)->sortorder; - if ($nextTask) - $targetOrder++; - - Activity::where("sortorder", ">=", $targetOrder)->increment("sortorder"); - - $updatedTask = Activity::find($taskId); - $updatedTask->sortorder = $targetOrder; - $updatedTask->save(); - } - - public function updateRegular(Request $request, $id) - { - if (empty($id) || !is_int((int) $id)) - return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); - - $data = Activity::find($id); - - if (!$data = Activity::find($id)) - return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); - - if (!$data->update($request->all())) - return response()->json(['status' => 'failed', 'message' => 'Failed to update!', 'code' => 500], 500); - - return response()->json(['status' => 'success', 'message' => 'Activity 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(); - $link = Link::where('version_gantt_id', $ganttId)->get(); - if (!$activity) - return response()->json(['status' => 'failed', 'message' => 'Activity not found!', 'code' => 404], 404); - if (!$link) - return response()->json(['status' => 'failed', 'message' => 'Link not found!', 'code' => 404], 404); - foreach ($entities as $entity) { - if ($entity['entity'] == "task") { - $activityToUpdate = $activity->firstWhere('id', $entity['data']['id']); - $entity['data']['name'] = $entity['data']['text']; - $entity['data']['persentase_progress'] = $entity['data']['progress'] * 100; - if (isset($entity['data']['target'])) { - $this->updateOrder($entity['data']['id'], $entity['data']['target']); - } - if(!$activityToUpdate->update($entity['data'])) - return response()->json(['status' => 'failed', 'message' => 'Failed to update activity !', 'code' => 500], 500); - $updatedJobsDone = $activityToUpdate->jobs_done; - } else if ($entity['entity'] == "link"){ - $linkToUpdate = $link->firstWhere('id', $entity['data']['id']); - if(!$linkToUpdate->update($entity['data'])) - return response()->json(['status' => 'failed', 'message' => 'Failed to update link !', 'code' => 500], 500); - } - } - return response()->json(['status' => 'success', 'message' => 'Activity Updated!', 'code' => 200], 200); - } - - public function delete($id) - { - if (!$data = Activity::find($id)) - return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 404], 404); - - 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); - } - - public function getUpdate($id) - { - if (!$data = Activity::find($id)) - return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 400], 400); - - $data->progress = (float) $data->persentase_progress / 100; - $data->rencana_biaya = str_replace(".", ",", $data->rencana_biaya); - return response()->json(['status' => 'success', "data" => $data, 'code' => 200], 200); - } - - public function search(Request $request) - { - $dataBuilder = $this->setUpPayload($request->all(), 'm_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); - } - - // before upload file - public function importOld(Request $request) - { - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - Activity::where('version_gantt_id', $data['ganttId'])->delete(); - - $projectId = VersionGantt::where('id', $data['ganttId'])->first()->proyek_id; - $dayOffs = VersionGantt::where('id', $data['ganttId'])->first()->config_dayoff; - - $activityStack = []; - - $hasWeight = false; - - foreach ($data['activities'] as $key => $value) { - if (isset($value['weight']) && $value['weight'] != null && $value['weight'] != 0) { - $hasWeight = true; - break; - } - } - - if (!$hasWeight) { - foreach ($data['activities'] as $key => $value) { - if ($key == 0) { - $data['activities'][$key]['weight'] = 100; - } else { - $parentWeight = 0; - $siblingsCount = 1; - - $i = $key; - while ($i > 0) { - if ($data['activities'][$i - 1]['level'] == $data['activities'][$key]['level'] - 1) { - $parentWeight = $data['activities'][$i - 1]['weight']; - break; - } - if ($data['activities'][$key]['level'] == $data['activities'][$i]['level']) { - $siblingsCount++; - } - $i--; - } - - $i = $key + 1; - while ($i < count($data['activities'])) { - if ($data['activities'][$i]['level'] == $data['activities'][$key]['level'] - 1) { - break; - } - // Log::info('level '.$data['activities'][$key]['level'].' i level '.$data['activities'][$i]['level']); - if ($data['activities'][$key]['level'] == $data['activities'][$i]['level']) { - $siblingsCount++; - } - $i++; - } - - $data['activities'][$key]['weight'] = $parentWeight / $siblingsCount; - } - } - ; - } - $projectStart = Project::select('mulai_proyek')->where('id', $projectId)->first(); - foreach ($data['activities'] as $i => $activity_row) { - $startDate = new \DateTime($projectStart->mulai_proyek); - $endDate = clone $startDate; - $endDate->modify('-1 day'); - $daysRemaining = $activity_row['duration']; - - // Loop until the remaining days become zero - while ($daysRemaining > 0) { - $endDate->modify('+1 day'); - - // Check if the current day is a day off (Sunday or Saturday) - $currentDayOfWeek = (int) $endDate->format('w'); - if (strpos($dayOffs, (string) $currentDayOfWeek) !== false) { - continue; // Skip the day off and continue to the next day - } - - $daysRemaining--; // Decrease the remaining days by one - } - $endDate->setTime(23, 59, 59); - $input['name'] = $activity_row['name']; - $input['proyek_id'] = $projectId; - $input['version_gantt_id'] = $data['ganttId']; - $input['parent_id'] = null; - $input['start_date'] = $startDate->format('Y-m-d'); - $input['end_date'] = $endDate->format('Y-m-d H:i:sO'); - $input['duration'] = $activity_row['duration']; - $input['bobot_planning'] = $activity_row['weight']; - $input['persentase_progress'] = 0; - $input['type_activity'] = $i == 0 ? "header" : "task"; - $input['created_by'] = $this->currentName; - $input['sortorder'] = $activity_row['no']; - - if (!$activity = Activity::create($input)) { - Activity::where('version_gantt_id', $data['ganttId'])->delete(); - return response()->json(['status' => 'error', 'message' => 'Input failed on ' . $activity['name'], 'code' => 500], 500); - } - - $data['activities'][$i]['activity_id'] = $activity->id; - - if ($i == 0) { - $activity->type_activity = "project"; - $activity->save(); - $activity->level = $activity_row['level']; - array_push($activityStack, $activity); - continue; - } - - $activity->level = $activity_row['level']; - - if ($lastStack = end($activityStack)) { - $levelLowerThanLastStack = $activity->level < $lastStack->level; - $levelEqualWithLastStack = $activity->level == $lastStack->level; - - if ($levelLowerThanLastStack) { - $lastStackIsNotRight = $levelLowerThanLastStack; - do { - array_pop($activityStack); - $lastStack = end($activityStack); - if ($lastStack) { - if ($activity->level > $lastStack->level) - $lastStackIsNotRight = false; - } else { - $lastStackIsNotRight = false; - } - } while ($lastStackIsNotRight); - } - - if ($levelEqualWithLastStack) { - array_pop($activityStack); - } - } - - $activity->parent_id = $activityStack[count($activityStack) - 1]->id ?? null; - array_push($activityStack, $activity); - // there should be better way to except / filter attribute level before save because it's cause error - // cant use except() / filter() on $activity collection somehow - unset($activity->level); - $activity->save(); - $activity->level = $activity_row['level']; - - if (@$activityStack[count($activityStack) - 1]->level != $activity->level && $activity->level != $data['activities'][$i - 1]['level']) { - array_push($activityStack, $activity); - } - - if ($activity->level < @$data['activities'][$i + 1]['level']) { - unset($activity->level); - $activity->type_activity = "project"; - $activity->save(); - $activity->level = $activity_row['level']; - } - if (isset($data['activities'][$i]['nik']) && $data['activities'][$i]['nik'] != '') { - $user = User::where("ktp_number", $data['activities'][$i]['nik'])->first(); - $userProyek = UserToProyek::where("user_id", $user->id) - ->where("proyek_id", $projectId) - ->first(); - - $dataInsert = array( - "user_id" => $user->id, - "activity_id" => $activity->id, - "role_proyek_id" => $userProyek->project_role, - "proyek_id" => $projectId, - "created_by" => $this->currentName, - "version_gantt_id" => $data['ganttId'] - ); - UserToActivity::create($dataInsert); - } - - if (!empty($activity_row['predecessor'])) { - $key = array_search($activity_row['predecessor'], array_column($data['activities'], 'no')); - - if (!isset($data['activities'][$key]['activity_id']) || !$predecessorActivity = Activity::find($data['activities'][$key]['activity_id'])) - continue; - - $predecessorFinishDate = new \DateTime($predecessorActivity->end_date); - $interval = $predecessorFinishDate->diff(new \DateTime($activity->start_date)); - $diff = $interval->days; - - Link::create([ - 'created_by' => $this->currentName, - 's_activity_id' => $predecessorActivity->id, - 't_activity_id' => $activity->id, - 'type_link' => 0, - 'code_link' => 'FS', - 'version_gantt_id' => $data['ganttId'], - 'lag' => null, - ]); - } - } - - return response()->json(['stack' => $activityStack, 'status' => 'success', 'message' => 'Data imported!', 'projectId' => $projectId, 'code' => 200], 200); - } - - private function getLatestGantt($id) - { - $maxGanttId = VersionGantt::where("proyek_id", $id)->max("id"); - $data = array( - "last_gantt_id" => $maxGanttId, - "proyek_id" => $id - ); - return $data; - } - - public function getCalculateCurvaS(Request $request) // for adw (plan & actual == date) - { - $dataPayload = $request->all(); - $allGantt = []; - if (isset($dataPayload['gannt_id'])) { - $allGantt = $dataPayload['gannt_id']; - } else { - foreach ($dataPayload['project_id'] as $val) { - $allGantt[] = $this->getLatestGantt($val); - } - } - $dataFinal = []; - foreach ($allGantt as $keyGantt) { - $dataProject = Project::find($keyGantt['proyek_id']); - $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['last_gantt_id'])->first(); - if ($dataHeader) { - $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['last_gantt_id'])->sum("rencana_biaya"); - } else { - $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['last_gantt_id'])->sum("rencana_biaya"); - } - $minDate = 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['last_gantt_id']) - ->min("plan_date"); - $maxDate = 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['last_gantt_id']) - ->max("plan_date"); - $begin = new \DateTime($minDate); - $end = new \DateTime($maxDate); - $end2 = new \DateTime($maxDate); - $interval = \DateInterval::createFromDateString('1 day'); - $period = new \DatePeriod($begin, $interval, $end); - $arr_ActualM = []; - $tempDate = []; - $tempPercentage = []; - $tempTtlPercentPlan = 0; - $tempTtlPercentActual = 0; - $currentACWP = 0; - $budgetControlACWP = 0; - $currentProgressActivity = 0; - $currentBCWP = 0; - $budgetControlBCWP = 0; - foreach ($period as $dt) { - $dataPlanM = DB::table('assign_material_to_activity as ama') - ->select('ama.activity_id', 'ama.qty_planning', 'ama.plan_date', 'ama.start_activity', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') - ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') - ->where('ama.proyek_id', '=', $keyGantt['proyek_id']) - ->where('a.version_gantt_id', '=', $keyGantt['last_gantt_id']) - ->whereDate('ama.plan_date', $dt->format("Y-m-d")) - ->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['last_gantt_id']) - ->where('a.proyek_id', '=', $keyGantt['proyek_id']) - ->whereDate('ram.report_date', $dt->format("Y-m-d")) - ->get(); - $dataTempPlan = []; - $x = 0; - $sumPercentagePlan = 0; - $totalACWP = isset($totalACWP) ? $totalACWP : 0; - $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; - foreach ($dataPlanM as $keyPlanM) { - $sumVolPlan = DB::table('assign_material_to_activity') - ->select('activity_id', DB::raw('SUM(qty_planning) as ttl_qty_plan')) - ->where('activity_id', '=', $keyPlanM->activity_id) - ->groupBy('activity_id') - ->first(); - $dataTempPlan[$x]['activity_id'] = $keyPlanM->activity_id; - $dataTempPlan[$x]['qty_plan'] = $keyPlanM->qty_planning; - $dataTempPlan[$x]['plan_date'] = $keyPlanM->plan_date; - $dataTempPlan[$x]['start_activity'] = $keyPlanM->start_activity; - $dataTempPlan[$x]['bobot_planning'] = $keyPlanM->bobot_planning; - $dataTempPlan[$x]['ttl_plan'] = $sumVolPlan->ttl_qty_plan; - $dataTempPlan[$x]['biaya_actual'] = $keyPlanM->biaya_actual; - $dataTempPlan[$x]['duration'] = $keyPlanM->duration; - $dataTempPlan[$x]['persentase_progress'] = $keyPlanM->persentase_progress; - $dataTempPlan[$x]['percentage'] = ($keyPlanM->qty_planning / $sumVolPlan->ttl_qty_plan) * $keyPlanM->bobot_planning; - $sumPercentagePlan += ($keyPlanM->qty_planning / $sumVolPlan->ttl_qty_plan) * $keyPlanM->bobot_planning; - $totalBCWP += (((($keyPlanM->persentase_progress * $keyPlanM->bobot_planning) / 100) / $keyPlanM->duration) * $totalRencanaBudget) / 100; - $dataTempPlan[$x]['totalBCWP'] = $totalBCWP; - $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(); - $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; - $dataTempReport[$w]['percentage'] = ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; - $sumPercentageActual += ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; - $totalACWP += $keyActualM->biaya_actual / $keyActualM->duration; - $dataTempReport[$w]['totalacwp'] = $totalACWP; - $w++; - } - $arr_ActualM[] = array( - 'date' => $dt->format("Y-m-d"), - 'percentPlan' => $sumPercentagePlan, - 'percentActual' => $sumPercentageActual, - 'plan' => $dataTempPlan, - 'actual' => $dataTempReport, - ); - if (isset($dataPayload['period']) && $dataPayload['period'] == 'week') { - if ($dt->format("w") == 1) { - if ($totalACWP > 0) { - $budgetControlACWP = $currentACWP + $totalACWP; - } - if ($totalBCWP > 0) { - $budgetControlBCWP = $currentBCWP + $totalBCWP; - } - $tempTtlPercentPlan += $sumPercentagePlan; - $tempTtlPercentActual += $sumPercentageActual; - $currentACWP += $totalACWP; - $currentBCWP += $totalBCWP; - $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); - $tempDate[] = array($dt->format("Y-m-d"), 0, 0); - } else if ($dt->format("Y-m-d") == $end2->format("Y-m-d")) { - $tempTtlPercentPlan += $sumPercentagePlan; - $tempTtlPercentActual += $sumPercentageActual; - $currentACWP += $totalACWP; - $currentBCWP += $totalBCWP; - $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); - $tempDate[] = array($dt->format("Y-m-d"), 0, 0); - $tempTtlPercentPlan = 0; - $tempTtlPercentActual = 0; - } - } else { - $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); - $tempDate[] = array($dt->format("Y-m-d"), 0, 0); - } - } - if (round($totalACWP, 0) > $totalRencanaBudget) { - $estimatedCost = round($totalACWP, 0) + 0; - } else { - $estimatedCost = ($totalRencanaBudget + 0); - } - $costDeviation = $totalRencanaBudget - $estimatedCost; - if ($costDeviation > 0) { - $potential = "SAVING"; - } else { - $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; - } - $dataResponse = array( - "date" => $tempDate, - "percentage" => $tempPercentage, - "data_details" => $arr_ActualM, - "budget_control" => array( - "current_budget" => $totalRencanaBudget, - "acwp" => round($totalACWP, 0), - "bcwp" => round($totalBCWP, 0), - "rem_to_complete" => ($totalRencanaBudget - round($totalACWP, 0)), - "add_cost_to_complete" => 0, - "estimated_at_completion" => $estimatedCost, - "cost_deviation" => $costDeviation, - "potential" => $potential, - ) - ); - $dataFinal[] = array( - "proyek_name" => $dataProject->nama, - "data" => $dataResponse, - "allGant" => $allGantt - ); - } - return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataFinal], 200); - } - - public function import(Request $request) - { - $data = $request->all(); - $data['created_by'] = $this->currentName; - Activity::where('version_gantt_id', $data['gantt_id'])->delete(); - $projectId = VersionGantt::where('id', $data['gantt_id'])->first()->proyek_id; - // get data excel - $excel = TmpImport::latest('id')->first(); - - return response()->json(['stack' => $excel, 'status' => 'success', 'message' => 'Data imported!', 'data' => $data, 'code' => 200], 200); - } - - public function uploadTmpImport(Request $request) - { - if ($request->hasFile('dokumen')) { - $document = $request->file('dokumen'); - $gantt_id = $request->gantt_id; - $name = $document->getClientOriginalName(); - - $result = $document->move($this->pathTmpImport, $name); - if ($result) { - $data = [ - 'gantt_id' => (int) $gantt_id, - 'file' => $name, - 'type_dokumen' => $request->type_dokumen - ]; - - $result = TmpImport::create($data); - - if (!$result) { - unlink($this->pathTmpImport . $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 importUpdate(Request $request) - { - $data = $request->all(); - foreach ($data as $value) { - $activity = Activity::find($value['id']); - $activity->duration = $value['duration']; - $activity->start_date = $value['start_date']; - $activity->end_date = $value['end_date']; - $activity->save(); - } - return response()->json(['status' => 'success', 'data' => $request, 'message' => 'Update successful!', 'code' => 200], 200); - } -} \ No newline at end of file +where("version_gantt_id", $id)->count() == 0) { + if (!$gantt->hierarchy_ftth_id) { + $this->cloneTemplate($id, $proyek_id); + } else { + $this->cloneTemplate($id, $proyek_id, $gantt->hierarchy_ftth_id); + } + } + + $dataGantt = $this->getDataActivity($id); + + return response()->json(['status' => 'success', 'data' => $dataGantt, 'code' => 200], 200); + } + + private function getDataActivity($id) + { + $checkHeader = Activity::where('version_gantt_id', $id)->where('type_activity', 'header')->count(); + $finalData = []; + if ($checkHeader > 0) { + $dataHeader = Activity::where('version_gantt_id', $id)->where('type_activity', 'header')->first(); + $startDate = date_create($dataHeader->start_date); + $endDate = date_create($dataHeader->end_date); + $dataHeader->start_date = date_format($startDate, "Y-m-d H:i:s"); + $dataHeader->end_date = date_format($endDate, "Y-m-d H:i:s"); + $dataHeader->progress = $dataHeader->persentase_progress / 100; + $dataHeader->planned_start = isset($dataHeader->planned_start) ? date_format(date_create($dataHeader->planned_start), "Y-m-d H:i:s") : NULL; + $dataHeader->planned_end = isset($dataHeader->planned_end) ? date_format(date_create($dataHeader->planned_end), "Y-m-d H:i:s") : NULL; + + $actualStart = $this->getFirstLastDateActivity($dataHeader->id, "start"); + $dataHeader->actual_start = date_format(date_create($actualStart), "Y-m-d"); + $actualEnd = $this->getFirstLastDateActivity($dataHeader->id, "end"); + $dataHeader->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "Y-m-d") : NULL; + + $dataHeader->type = "header"; + $dataHeader->text = $dataHeader->name; + $finalData[] = $dataHeader; + $data = Activity::where('version_gantt_id', $id)->where('parent_id', $dataHeader->id)->orderBy('sortorder', 'asc')->get(); + } else { + $data = Activity::where('version_gantt_id', $id)->whereNull('parent_id')->orderBy('sortorder', 'asc')->get(); + } + + foreach ($data as $objRow) { + $type = "project"; + $dataChildren = $this->getChildren($id, $objRow->id); + $startDate = date_create($objRow->start_date); + $endDate = date_create($objRow->end_date); + + if ($objRow->type_activity == "milestone") + $type = $objRow->type_activity; + if (empty($dataChildren)) + $type = "task"; + + $objRow->text = $objRow->name; + $objRow->parent = $objRow->parent_id ? $objRow->parent_id : null; + $objRow->start_date = date_format($startDate, "Y-m-d H:i:s"); + $objRow->end_date = date_format($endDate, "Y-m-d H:i:s"); + $objRow->planned_start = isset($objRow->planned_start) ? date_format(date_create($objRow->planned_start), "Y-m-d H:i:s") : NULL; + $objRow->planned_end = isset($objRow->planned_end) ? date_format(date_create($objRow->planned_end), "Y-m-d H:i:s") : NULL; + + $actualStart = $this->getFirstLastDateActivity($objRow->id, "start"); + $objRow->actual_start = isset($actualStart) ? date_format(date_create($actualStart), "Y-m-d") : NULL; + $actualEnd = $this->getFirstLastDateActivity($objRow->id, "end"); + $objRow->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "Y-m-d") : NULL; + + $objRow->progress = $objRow->persentase_progress / 100; + $objRow->type = $type; + $finalData[] = $objRow; + $finalData = array_merge($finalData, $dataChildren); + } + + $dataLink = Link::where('version_gantt_id', $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 $resultData; + } + + private function getChildren($gantt_id, $parent_id) + { + $finalData = []; + $data = Activity::where('version_gantt_id', $gantt_id)->where('parent_id', $parent_id)->orderBy('sortorder', 'asc')->get(); + foreach ($data as $objRow) { + $objRow->parent = $parent_id; + $objRow->text = $objRow->name; + $objRow->progress = (float) $objRow->persentase_progress / 100; + $startDate = date_create($objRow->start_date); + $endDate = date_create($objRow->end_date); + $objRow->start_date = date_format($startDate, "Y-m-d H:i:s"); + $objRow->end_date = date_format($endDate, "Y-m-d H:i:s"); + $objRow->planned_start = isset($objRow->planned_start) ? date_format(date_create($objRow->planned_start), "Y-m-d H:i:s") : NULL; + $objRow->planned_end = isset($objRow->planned_end) ? date_format(date_create($objRow->planned_end), "Y-m-d H:i:s") : NULL; + + $dataChildren = $this->getChildren($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), "Y-m-d") : NULL; + } elseif (empty($dataChildren)) { + $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)){ + $objRow->auto_scheduling = false; + } + } else { + $objRow->type = "project"; + $actualStart = $this->getFirstLastDateActivity($objRow->id, "start"); + $objRow->actual_start = isset($actualStart) ? date_format(date_create($actualStart), "Y-m-d") : NULL; + + $actualEnd = $this->getFirstLastDateActivity($objRow->id, "end"); + $objRow->actual_end = isset($actualEnd) ? date_format(date_create($actualEnd), "Y-m-d") : NULL; + } + $finalData[] = $objRow; + $finalData = array_merge($finalData, $dataChildren); + } + return $finalData; + } + + 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"){ + // Log::info("activity ", [$activity]); + return $activity->actual_start; + }else{ + return $this->getActivityFirst($activity->id); + } + + } + + public function getFirstLastDateActivity($id, $params){ + if($params == "start"){ + $data = Activity::select('id', 'parent_id', 'name', 'actual_start')->where('parent_id', $id)->get(); + }else{ + $data = Activity::select('id', 'parent_id', 'name', 'actual_end')->where('parent_id', $id)->get(); + } + $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) { + return isset($item['actual_start']); + }), 'actual_start'); + + $returnActualStartOrEnd = count($actualStartValues) > 0 ? min($actualStartValues) : null; + }else{ + $actualEndValues = array_column(array_filter($dataFinal, function($item) { + return isset($item['actual_end']); + }), 'actual_end'); + + $returnActualStartOrEnd = count($actualEndValues) > 0 ? max($actualEndValues) : null; + } + + // return json_encode(["min"=>$minActualStart, "max"=>$maxActualStart]); + return $returnActualStartOrEnd; + } + + public function getchildActivityForActual($parent, $params){ + if($params == "start"){ + $activity = Activity::select('id', 'actual_start')->where('parent_id', $parent)->get(); + }else{ + $activity = Activity::select('id', 'actual_end')->where('parent_id', $parent)->get(); + } + $temp = []; + foreach($activity as $val1){ + $getChild = $this->getchildActivityForActual($val1->id, $params); + $temp[] = $val1; + $temp = array_merge($temp, $getChild); + } + return $temp; + } + + 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"){ + // Log::info("activity ", [$activity]); + return $activity->actual_end; + }else{ + return $this->getActivityLast($activity->id); + } + + } + + private function cloneTemplate($id, $proyek_id, $hierarchy_ftth_id = null) + { + $project = Project::find($proyek_id); + if ($hierarchy_ftth_id) { + $gantt = VersionGantt::find($id); + $rootActivity = Activity::create([ + 'version_gantt_id' => $id, + 'proyek_id' => $proyek_id, + 'name' => $gantt->name_version, + 'start_date' => $project->mulai_proyek, + 'end_date' => $project->akhir_proyek, + 'rencana_biaya' => $project->rencana_biaya, + 'type_activity' => 'project', + 'created_by' => $this->currentName, + 'sortorder' => 1 + ]); + } else { + $rootActivity = Activity::create([ + 'version_gantt_id' => $id, + 'proyek_id' => $proyek_id, + 'name' => $project->nama, + 'kode_sortname' => $project->kode_sortname, + 'start_date' => $project->mulai_proyek, + 'end_date' => $project->akhir_proyek, + 'rencana_biaya' => $project->rencana_biaya, + 'type_activity' => 'project', + 'created_by' => $this->currentName, + 'sortorder' => 1 + ]); + } + + $resultTypeProject = TemplateGantt::where('proyek_type_id', $project->type_proyek_id) + ->whereNull('parent_id') + ->orderByRaw('id ASC') + ->get(); + + foreach ($resultTypeProject as $objRow) { + $childActivities = TemplateGantt::where("parent_id", $objRow->id)->count(); + $max = Activity::where('version_gantt_id', $id)->max('sortorder'); + $resultNew = Activity::create([ + 'type_activity' => $childActivities > 0 ? "project" : "task", + 'version_gantt_id' => $id, + 'parent_id' => $rootActivity->id, + 'proyek_id' => $proyek_id, + 'name' => $objRow->name_activity, + 'start_date' => date("Y-m-d H:i:s"), + 'end_date' => date("Y-m-d H:i:s"), + 'created_by' => $this->currentName, + 'sortorder' => $max + 1 + ]); + $this->getChildrenTemplate($id, $objRow->id, $project->type_project_id, $proyek_id, $resultNew->id, $project->mulai_proyek); + } + } + + private function getChildrenTemplate($id, $parent_id, $type_proyek_id, $proyek_id, $parent_new, $firstDay) + { + $data = TemplateGantt::where('parent_id', $parent_id)->orderByRaw('id ASC')->get(); + foreach ($data as $objRow) { + $childActivities = TemplateGantt::where("parent_id", $objRow->id)->count(); + $max = Activity::where('version_gantt_id', $id)->max('sortorder'); + $resultNew = Activity::create([ + 'type_activity' => $childActivities > 0 ? "project" : "task", + 'version_gantt_id' => $id, + 'parent_id' => $parent_new, + 'proyek_id' => $proyek_id, + 'name' => $objRow->name_activity, + 'start_date' => $firstDay, + 'end_date' => $firstDay, + 'created_by' => $this->currentName, + 'sortorder' => $max + 1 + ]); + $this->getChildrenTemplate($id, $objRow->id, $type_proyek_id, $proyek_id, $resultNew->id, $firstDay); + } + } + + public function add(Request $request) + { + $this->validate($request, [ + 'version_gantt_id' => 'required' + ]); + + $data = $request->all(); + $data['name'] = $request->text; + $data['persentase_progress'] = $request->progress; + $data['created_by'] = $this->currentName; + $max = Activity::where('version_gantt_id', $request->version_gantt_id)->max('sortorder'); + $data['sortorder'] = $max + 1; + if (!isset($data['type_activity'])) { + $data['type_activity'] = "task"; + } + + $parent = $data['parent_id'] ?? null; + if ($parent) { + $parentData = Activity::find($parent); + if ($parentData->parent_id) { + $parentData->update(["type_activity" => "project"]); + } + CommentActivity::where('activity_id', $parent)->delete(); + UserToActivity::where('activity_id', $parent)->delete(); + } + + if (!$result = Activity::create($data)) + return response()->json(['status' => 'failed', 'action' => 'error', 'code' => 500], 500); + + return response()->json(['status' => 'success', 'action' => 'inserted', 'tid' => $result->id, '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); + + if (!$result = Activity::find($id)) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + + return response()->json(['status' => 'success', 'code' => 200, 'data' => $result], 200); + } + + public function update(Request $request, $id) + { + if (empty($id) || !is_int((int) $id)) + return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'id is required!', 'code' => 400], 400); + + $updateBobot = true; + if (!$data = Activity::find($id)) + return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 404], 404); + $dataUpdate = $request->all(); + + $dataUpdate['name'] = $request->text; + $dataUpdate['persentase_progress'] = $request->progress * 100; + $dataUpdate['updated_by'] = $this->currentName; + unset($dataUpdate['sortorder']); + if ($data->type_activity != 'header') + $dataUpdate['type_activity'] = $request->type; + + if ($request->has("target")) { + $this->updateOrder($id, $request->target); + } + + if (!$data->update($dataUpdate)) + return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'data activity failed updated!', 'code' => 400], 400); + + return response()->json(['status' => 'success', 'update_bobot' => $updateBobot, 'data' => $dataUpdate, 'action' => 'updated', 'message' => 'Activity updated!', 'code' => 200], 200); + } + + private function updateOrder($taskId, $target) + { + $nextTask = false; + $targetId = $target; + + if (strpos($target, "next:") === 0) { + $targetId = substr($target, strlen("next:")); + $nextTask = true; + } + + if ($targetId == "null") + return; + + $targetOrder = Activity::find($targetId)->sortorder; + if ($nextTask) + $targetOrder++; + + Activity::where("sortorder", ">=", $targetOrder)->increment("sortorder"); + + $updatedTask = Activity::find($taskId); + $updatedTask->sortorder = $targetOrder; + $updatedTask->save(); + } + + public function updateRegular(Request $request, $id) + { + if (empty($id) || !is_int((int) $id)) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); + + $data = Activity::find($id); + + if (!$data = Activity::find($id)) + return response()->json(['status' => 'failed', 'message' => 'Data not found!', 'code' => 404], 404); + + if (!$data->update($request->all())) + return response()->json(['status' => 'failed', 'message' => 'Failed to update!', 'code' => 500], 500); + + return response()->json(['status' => 'success', 'message' => 'Activity 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(); + $link = Link::where('version_gantt_id', $ganttId)->get(); + if (!$activity) + return response()->json(['status' => 'failed', 'message' => 'Activity not found!', 'code' => 404], 404); + if (!$link) + return response()->json(['status' => 'failed', 'message' => 'Link not found!', 'code' => 404], 404); + foreach ($entities as $entity) { + if ($entity['entity'] == "task") { + $activityToUpdate = $activity->firstWhere('id', $entity['data']['id']); + $entity['data']['name'] = $entity['data']['text']; + $entity['data']['persentase_progress'] = $entity['data']['progress'] * 100; + if (isset($entity['data']['target'])) { + $this->updateOrder($entity['data']['id'], $entity['data']['target']); + } + if(!$activityToUpdate->update($entity['data'])) + return response()->json(['status' => 'failed', 'message' => 'Failed to update activity !', 'code' => 500], 500); + $updatedJobsDone = $activityToUpdate->jobs_done; + } else if ($entity['entity'] == "link"){ + $linkToUpdate = $link->firstWhere('id', $entity['data']['id']); + if(!$linkToUpdate->update($entity['data'])) + return response()->json(['status' => 'failed', 'message' => 'Failed to update link !', 'code' => 500], 500); + } + } + return response()->json(['status' => 'success', 'message' => 'Activity Updated!', 'code' => 200], 200); + } + + public function delete($id) + { + if (!$data = Activity::find($id)) + return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 404], 404); + + 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); + } + + public function getUpdate($id) + { + if (!$data = Activity::find($id)) + return response()->json(['status' => 'failed', 'action' => 'error', 'message' => 'Data not found!', 'code' => 400], 400); + + $data->progress = (float) $data->persentase_progress / 100; + $data->rencana_biaya = str_replace(".", ",", $data->rencana_biaya); + return response()->json(['status' => 'success', "data" => $data, 'code' => 200], 200); + } + + public function search(Request $request) + { + $dataBuilder = $this->setUpPayload($request->all(), 'm_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); + } + + // before upload file + public function importOld(Request $request) + { + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + Activity::where('version_gantt_id', $data['ganttId'])->delete(); + + $projectId = VersionGantt::where('id', $data['ganttId'])->first()->proyek_id; + $dayOffs = VersionGantt::where('id', $data['ganttId'])->first()->config_dayoff; + + $activityStack = []; + + $hasWeight = false; + + foreach ($data['activities'] as $key => $value) { + if (isset($value['weight']) && $value['weight'] != null && $value['weight'] != 0) { + $hasWeight = true; + break; + } + } + + if (!$hasWeight) { + foreach ($data['activities'] as $key => $value) { + if ($key == 0) { + $data['activities'][$key]['weight'] = 100; + } else { + $parentWeight = 0; + $siblingsCount = 1; + + $i = $key; + while ($i > 0) { + if ($data['activities'][$i - 1]['level'] == $data['activities'][$key]['level'] - 1) { + $parentWeight = $data['activities'][$i - 1]['weight']; + break; + } + if ($data['activities'][$key]['level'] == $data['activities'][$i]['level']) { + $siblingsCount++; + } + $i--; + } + + $i = $key + 1; + while ($i < count($data['activities'])) { + if ($data['activities'][$i]['level'] == $data['activities'][$key]['level'] - 1) { + break; + } + // Log::info('level '.$data['activities'][$key]['level'].' i level '.$data['activities'][$i]['level']); + if ($data['activities'][$key]['level'] == $data['activities'][$i]['level']) { + $siblingsCount++; + } + $i++; + } + + $data['activities'][$key]['weight'] = $parentWeight / $siblingsCount; + } + } + ; + } + $projectStart = Project::select('mulai_proyek')->where('id', $projectId)->first(); + foreach ($data['activities'] as $i => $activity_row) { + $startDate = new \DateTime($projectStart->mulai_proyek); + $endDate = clone $startDate; + $endDate->modify('-1 day'); + $daysRemaining = $activity_row['duration']; + + // Loop until the remaining days become zero + while ($daysRemaining > 0) { + $endDate->modify('+1 day'); + + // Check if the current day is a day off (Sunday or Saturday) + $currentDayOfWeek = (int) $endDate->format('w'); + if (strpos($dayOffs, (string) $currentDayOfWeek) !== false) { + continue; // Skip the day off and continue to the next day + } + + $daysRemaining--; // Decrease the remaining days by one + } + $endDate->setTime(23, 59, 59); + $input['name'] = $activity_row['name']; + $input['proyek_id'] = $projectId; + $input['version_gantt_id'] = $data['ganttId']; + $input['parent_id'] = null; + $input['start_date'] = $startDate->format('Y-m-d'); + $input['end_date'] = $endDate->format('Y-m-d H:i:sO'); + $input['duration'] = $activity_row['duration']; + $input['bobot_planning'] = $activity_row['weight']; + $input['persentase_progress'] = 0; + $input['type_activity'] = $i == 0 ? "header" : "task"; + $input['created_by'] = $this->currentName; + $input['sortorder'] = $activity_row['no']; + + if (!$activity = Activity::create($input)) { + Activity::where('version_gantt_id', $data['ganttId'])->delete(); + return response()->json(['status' => 'error', 'message' => 'Input failed on ' . $activity['name'], 'code' => 500], 500); + } + + $data['activities'][$i]['activity_id'] = $activity->id; + + if ($i == 0) { + $activity->type_activity = "project"; + $activity->save(); + $activity->level = $activity_row['level']; + array_push($activityStack, $activity); + continue; + } + + $activity->level = $activity_row['level']; + + if ($lastStack = end($activityStack)) { + $levelLowerThanLastStack = $activity->level < $lastStack->level; + $levelEqualWithLastStack = $activity->level == $lastStack->level; + + if ($levelLowerThanLastStack) { + $lastStackIsNotRight = $levelLowerThanLastStack; + do { + array_pop($activityStack); + $lastStack = end($activityStack); + if ($lastStack) { + if ($activity->level > $lastStack->level) + $lastStackIsNotRight = false; + } else { + $lastStackIsNotRight = false; + } + } while ($lastStackIsNotRight); + } + + if ($levelEqualWithLastStack) { + array_pop($activityStack); + } + } + + $activity->parent_id = $activityStack[count($activityStack) - 1]->id ?? null; + array_push($activityStack, $activity); + // there should be better way to except / filter attribute level before save because it's cause error + // cant use except() / filter() on $activity collection somehow + unset($activity->level); + $activity->save(); + $activity->level = $activity_row['level']; + + if (@$activityStack[count($activityStack) - 1]->level != $activity->level && $activity->level != $data['activities'][$i - 1]['level']) { + array_push($activityStack, $activity); + } + + if ($activity->level < @$data['activities'][$i + 1]['level']) { + unset($activity->level); + $activity->type_activity = "project"; + $activity->save(); + $activity->level = $activity_row['level']; + } + if (isset($data['activities'][$i]['nik']) && $data['activities'][$i]['nik'] != '') { + $user = User::where("ktp_number", $data['activities'][$i]['nik'])->first(); + $userProyek = UserToProyek::where("user_id", $user->id) + ->where("proyek_id", $projectId) + ->first(); + + $dataInsert = array( + "user_id" => $user->id, + "activity_id" => $activity->id, + "role_proyek_id" => $userProyek->project_role, + "proyek_id" => $projectId, + "created_by" => $this->currentName, + "version_gantt_id" => $data['ganttId'] + ); + UserToActivity::create($dataInsert); + } + + if (!empty($activity_row['predecessor'])) { + $key = array_search($activity_row['predecessor'], array_column($data['activities'], 'no')); + + if (!isset($data['activities'][$key]['activity_id']) || !$predecessorActivity = Activity::find($data['activities'][$key]['activity_id'])) + continue; + + $predecessorFinishDate = new \DateTime($predecessorActivity->end_date); + $interval = $predecessorFinishDate->diff(new \DateTime($activity->start_date)); + $diff = $interval->days; + + Link::create([ + 'created_by' => $this->currentName, + 's_activity_id' => $predecessorActivity->id, + 't_activity_id' => $activity->id, + 'type_link' => 0, + 'code_link' => 'FS', + 'version_gantt_id' => $data['ganttId'], + 'lag' => null, + ]); + } + } + + return response()->json(['stack' => $activityStack, 'status' => 'success', 'message' => 'Data imported!', 'projectId' => $projectId, 'code' => 200], 200); + } + + private function getLatestGantt($id) + { + $maxGanttId = VersionGantt::where("proyek_id", $id)->max("id"); + $data = array( + "last_gantt_id" => $maxGanttId, + "proyek_id" => $id + ); + return $data; + } + + public function getCalculateCurvaS(Request $request) // for adw (plan & actual == date) + { + $dataPayload = $request->all(); + $allGantt = []; + if (isset($dataPayload['gannt_id'])) { + $allGantt = $dataPayload['gannt_id']; + } else { + foreach ($dataPayload['project_id'] as $val) { + $allGantt[] = $this->getLatestGantt($val); + } + } + $dataFinal = []; + foreach ($allGantt as $keyGantt) { + $dataProject = Project::find($keyGantt['proyek_id']); + $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['last_gantt_id'])->first(); + if ($dataHeader) { + $totalRencanaBudget = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['last_gantt_id'])->sum("rencana_biaya"); + } else { + $totalRencanaBudget = Activity::whereNull('parent_id')->where("proyek_id", $keyGantt['proyek_id'])->where("version_gantt_id", $keyGantt['last_gantt_id'])->sum("rencana_biaya"); + } + $minDate = 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['last_gantt_id']) + ->min("plan_date"); + $maxDate = 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['last_gantt_id']) + ->max("plan_date"); + $begin = new \DateTime($minDate); + $end = new \DateTime($maxDate); + $end2 = new \DateTime($maxDate); + $interval = \DateInterval::createFromDateString('1 day'); + $period = new \DatePeriod($begin, $interval, $end); + $arr_ActualM = []; + $tempDate = []; + $tempPercentage = []; + $tempTtlPercentPlan = 0; + $tempTtlPercentActual = 0; + $currentACWP = 0; + $budgetControlACWP = 0; + $currentProgressActivity = 0; + $currentBCWP = 0; + $budgetControlBCWP = 0; + foreach ($period as $dt) { + $dataPlanM = DB::table('assign_material_to_activity as ama') + ->select('ama.activity_id', 'ama.qty_planning', 'ama.plan_date', 'ama.start_activity', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') + ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') + ->where('ama.proyek_id', '=', $keyGantt['proyek_id']) + ->where('a.version_gantt_id', '=', $keyGantt['last_gantt_id']) + ->whereDate('ama.plan_date', $dt->format("Y-m-d")) + ->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['last_gantt_id']) + ->where('a.proyek_id', '=', $keyGantt['proyek_id']) + ->whereDate('ram.report_date', $dt->format("Y-m-d")) + ->get(); + $dataTempPlan = []; + $x = 0; + $sumPercentagePlan = 0; + $totalACWP = isset($totalACWP) ? $totalACWP : 0; + $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; + foreach ($dataPlanM as $keyPlanM) { + $sumVolPlan = DB::table('assign_material_to_activity') + ->select('activity_id', DB::raw('SUM(qty_planning) as ttl_qty_plan')) + ->where('activity_id', '=', $keyPlanM->activity_id) + ->groupBy('activity_id') + ->first(); + $dataTempPlan[$x]['activity_id'] = $keyPlanM->activity_id; + $dataTempPlan[$x]['qty_plan'] = $keyPlanM->qty_planning; + $dataTempPlan[$x]['plan_date'] = $keyPlanM->plan_date; + $dataTempPlan[$x]['start_activity'] = $keyPlanM->start_activity; + $dataTempPlan[$x]['bobot_planning'] = $keyPlanM->bobot_planning; + $dataTempPlan[$x]['ttl_plan'] = $sumVolPlan->ttl_qty_plan; + $dataTempPlan[$x]['biaya_actual'] = $keyPlanM->biaya_actual; + $dataTempPlan[$x]['duration'] = $keyPlanM->duration; + $dataTempPlan[$x]['persentase_progress'] = $keyPlanM->persentase_progress; + $dataTempPlan[$x]['percentage'] = ($keyPlanM->qty_planning / $sumVolPlan->ttl_qty_plan) * $keyPlanM->bobot_planning; + $sumPercentagePlan += ($keyPlanM->qty_planning / $sumVolPlan->ttl_qty_plan) * $keyPlanM->bobot_planning; + $totalBCWP += (((($keyPlanM->persentase_progress * $keyPlanM->bobot_planning) / 100) / $keyPlanM->duration) * $totalRencanaBudget) / 100; + $dataTempPlan[$x]['totalBCWP'] = $totalBCWP; + $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(); + $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; + $dataTempReport[$w]['percentage'] = ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; + $sumPercentageActual += ($keyActualM->qty / $sumVolActual->ttl_qty_plan) * $keyActualM->bobot_planning; + $totalACWP += $keyActualM->biaya_actual / $keyActualM->duration; + $dataTempReport[$w]['totalacwp'] = $totalACWP; + $w++; + } + $arr_ActualM[] = array( + 'date' => $dt->format("Y-m-d"), + 'percentPlan' => $sumPercentagePlan, + 'percentActual' => $sumPercentageActual, + 'plan' => $dataTempPlan, + 'actual' => $dataTempReport, + ); + if (isset($dataPayload['period']) && $dataPayload['period'] == 'week') { + if ($dt->format("w") == 1) { + if ($totalACWP > 0) { + $budgetControlACWP = $currentACWP + $totalACWP; + } + if ($totalBCWP > 0) { + $budgetControlBCWP = $currentBCWP + $totalBCWP; + } + $tempTtlPercentPlan += $sumPercentagePlan; + $tempTtlPercentActual += $sumPercentageActual; + $currentACWP += $totalACWP; + $currentBCWP += $totalBCWP; + $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); + $tempDate[] = array($dt->format("Y-m-d"), 0, 0); + } else if ($dt->format("Y-m-d") == $end2->format("Y-m-d")) { + $tempTtlPercentPlan += $sumPercentagePlan; + $tempTtlPercentActual += $sumPercentageActual; + $currentACWP += $totalACWP; + $currentBCWP += $totalBCWP; + $tempPercentage[] = array(round($tempTtlPercentPlan, 2), round($tempTtlPercentActual, 2)); + $tempDate[] = array($dt->format("Y-m-d"), 0, 0); + $tempTtlPercentPlan = 0; + $tempTtlPercentActual = 0; + } + } else { + $tempPercentage[] = array(round($sumPercentagePlan, 2), round($sumPercentageActual, 2)); + $tempDate[] = array($dt->format("Y-m-d"), 0, 0); + } + } + if (round($totalACWP, 0) > $totalRencanaBudget) { + $estimatedCost = round($totalACWP, 0) + 0; + } else { + $estimatedCost = ($totalRencanaBudget + 0); + } + $costDeviation = $totalRencanaBudget - $estimatedCost; + if ($costDeviation > 0) { + $potential = "SAVING"; + } else { + $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; + } + $dataResponse = array( + "date" => $tempDate, + "percentage" => $tempPercentage, + "data_details" => $arr_ActualM, + "budget_control" => array( + "current_budget" => $totalRencanaBudget, + "acwp" => round($totalACWP, 0), + "bcwp" => round($totalBCWP, 0), + "rem_to_complete" => ($totalRencanaBudget - round($totalACWP, 0)), + "add_cost_to_complete" => 0, + "estimated_at_completion" => $estimatedCost, + "cost_deviation" => $costDeviation, + "potential" => $potential, + ) + ); + $dataFinal[] = array( + "proyek_name" => $dataProject->nama, + "data" => $dataResponse, + "allGant" => $allGantt + ); + } + return response()->json(['status' => 'success', 'code' => 200, 'data' => $dataFinal], 200); + } + + public function import(Request $request) + { + $data = $request->all(); + $data['created_by'] = $this->currentName; + Activity::where('version_gantt_id', $data['gantt_id'])->delete(); + $projectId = VersionGantt::where('id', $data['gantt_id'])->first()->proyek_id; + // get data excel + $excel = TmpImport::latest('id')->first(); + + return response()->json(['stack' => $excel, 'status' => 'success', 'message' => 'Data imported!', 'data' => $data, 'code' => 200], 200); + } + + public function uploadTmpImport(Request $request) + { + if ($request->hasFile('dokumen')) { + $document = $request->file('dokumen'); + $gantt_id = $request->gantt_id; + $name = $document->getClientOriginalName(); + + $result = $document->move($this->pathTmpImport, $name); + if ($result) { + $data = [ + 'gantt_id' => (int) $gantt_id, + 'file' => $name, + 'type_dokumen' => $request->type_dokumen + ]; + + $result = TmpImport::create($data); + + if (!$result) { + unlink($this->pathTmpImport . $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 importUpdate(Request $request) + { + $data = $request->all(); + foreach ($data as $value) { + $activity = Activity::find($value['id']); + $activity->duration = $value['duration']; + $activity->start_date = $value['start_date']; + $activity->end_date = $value['end_date']; + $activity->save(); + } + return response()->json(['status' => 'success', 'data' => $request, 'message' => 'Update successful!', 'code' => 200], 200); + } +} diff --git a/app/Http/Controllers/AssignMaterialController.php b/app/Http/Controllers/AssignMaterialController.php index b3f917a..3d78384 100644 --- a/app/Http/Controllers/AssignMaterialController.php +++ b/app/Http/Controllers/AssignMaterialController.php @@ -1,215 +1,221 @@ -validate($request, [ - 'activity_id' => 'required', - 'material_id' => 'required', - 'qty_planning' => 'required' - ]); - - $activity = Activity::where('id', $request->activity_id)->first(); - - $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]); - } - - $start_date = $activity->start_date; - $start_date = substr($start_date, 0, 19); // remove the timezone offset - $startDate = new \DateTime(date("Y-m-d", strtotime($start_date))); - $planDate = new \DateTime(date("Y-m-d", strtotime($request->plan_date))); - - $data = $request->all(); - $data['created_by'] = $this->currentName; - $data['budget'] = $checkStock->price; - $data['qty_planning'] = $this->sanitizeDecimal($data['qty_planning']); - - 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); - } - } - - public function update(Request $request, $id){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $data = AssignMaterial::find($id); - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); - - $result = $data->update($request->all()); - - if($result) - return response()->json(['status'=>'success','message'=> 'Data updated!','code'=> 200], 200); - - return response()->json(['status'=>'failed','message'=>'Failed to update!','code'=> 500], 500); - } - - public function delete($id) - { - $data = AssignMaterial::where('id', $id)->first(); - - if($data->delete()) - return response()->json(['status'=>'success','message'=>'Data deleted!','code'=> 200], 200); - - return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=> 500], 500); - } - - public function edit($id){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $result = AssignMaterial::find($id); - - if($result) - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'assign_material_to_activity'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = AssignMaterial::all(); - $countData = $data->count(); - - if($data) - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - - return response()->json(['status'=>'failed','message'=>'Failed to get the data!','code'=> 500], 500); - } - - public function datatables(Request $request){ - $id_activity = $request->query('idact'); - $type = $request->query('type') ?? "material"; - $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('assign_material_to_activity.type', $type) - ->orderBy('plan_date', 'desc') - ->get(); - return Datatables::of($data) - ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; - return $actionBtn; - }) - ->rawColumns(['action'])->make(true); - } - - public function datatablesForReportActivity(Request $request){ - $id_activity = $request->query('idact'); - $data = - AssignMaterial::select( - AssignMaterial::raw('SUM(qty_planning) as qty_planning'), - "m.description as material_name", - "assign_material_to_activity.activity_id", - "assign_material_to_activity.type" - // "assign_material_to_activity.material_id", - ) - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->groupBy("m.description") - ->groupBy("assign_material_to_activity.activity_id") - ->groupBy("assign_material_to_activity.type") - ->where("assign_material_to_activity.activity_id", $id_activity)->get(); - return Datatables::of($data) - ->addIndexColumn() - ->addColumn('qty_sum', function($row){ - $val_qty_act = AssignMaterial::select(ReportActivityMaterial::raw('SUM(ram.qty) as qty_sum'),"m.description as material_name1") - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->join("report_activity_material as ram", "ram.assign_material_id", "=", "assign_material_to_activity.id") - ->groupBy("m.description") - ->where("m.description", strval($row->material_name)) - ->where("ram.activity_id", $row->activity_id)->first(); - return $val_qty_act ? $val_qty_act->qty_sum : '-'; - }) - ->addColumn('status_activity', function($row){ - $val_status = AssignMaterial::select("status_activity") - ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') - ->where('m.description', '=', $row->material_name) - ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); - return $val_status ? $val_status->status_activity : null; - }) - ->addColumn('start_activity', function($row){ - $val_start = AssignMaterial::select("start_activity") - ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') - ->where('m.description', '=', $row->material_name) - ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); - return $val_start ? $val_start->start_activity : null; - }) - ->addColumn('finish_activity', function($row){ - $val_finish = AssignMaterial::select("finish_activity") - ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') - ->where('m.description', '=', $row->material_name) - ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); - return $val_finish ? $val_finish->finish_activity : null; - }) - ->addColumn('uom', function($row){ - $val_uom = RequestMaterial::select("uom") - ->where('description', '=', $row->material_name)->first(); - return $val_uom ? $val_uom->uom : null; - }) - ->addColumn('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){ - $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 .= ''; - return $actionBtn; - }) - ->rawColumns(['action'])->make(true); - } - - public function ForReportActivityByMaterial(Request $request){ - $id_activity = $request->idact; - $data = AssignMaterial::select("assign_material_to_activity.*","m.description as material_name", "m.uom as uom") - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->where('assign_material_to_activity.activity_id', $id_activity)->get(); - foreach ($data as $key) { - $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); - } - } -} +validate($request, [ + 'activity_id' => 'required', + 'material_id' => 'required', + 'qty_planning' => 'required' + ]); + + $activity = Activity::where('id', $request->activity_id)->first(); + + $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]); + } + + $start_date = $activity->start_date; + $start_date = substr($start_date, 0, 19); // remove the timezone offset + $startDate = new \DateTime(date("Y-m-d", strtotime($start_date))); + $planDate = new \DateTime(date("Y-m-d", strtotime($request->plan_date))); + + $data = $request->all(); + $data['created_by'] = $this->currentName; + $data['budget'] = $checkStock->price; + $data['qty_planning'] = $this->sanitizeDecimal($data['qty_planning']); + + 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); + } + } + + public function update(Request $request, $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = AssignMaterial::find($id); + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + $result = $data->update($request->all()); + + if($result) + return response()->json(['status'=>'success','message'=> 'Data updated!','code'=> 200], 200); + + return response()->json(['status'=>'failed','message'=>'Failed to update!','code'=> 500], 500); + } + + public function delete($id) + { + $data = AssignMaterial::where('id', $id)->first(); + $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); + + return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=> 500], 500); + } + + public function edit($id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $result = AssignMaterial::find($id); + + if($result) + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'assign_material_to_activity'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = AssignMaterial::all(); + $countData = $data->count(); + + if($data) + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + + return response()->json(['status'=>'failed','message'=>'Failed to get the data!','code'=> 500], 500); + } + + public function datatables(Request $request){ + $id_activity = $request->query('idact'); + $type = $request->query('type') ?? "material"; + $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('assign_material_to_activity.type', $type) + ->orderBy('plan_date', 'desc') + ->get(); + return Datatables::of($data) + ->addIndexColumn() + ->addColumn('action', function($row){ + $actionBtn = ''; + return $actionBtn; + }) + ->rawColumns(['action'])->make(true); + } + + public function datatablesForReportActivity(Request $request){ + $id_activity = $request->query('idact'); + $data = + AssignMaterial::select( + AssignMaterial::raw('SUM(qty_planning) as qty_planning'), + "m.description as material_name", + "assign_material_to_activity.activity_id", + "assign_material_to_activity.type" + // "assign_material_to_activity.material_id", + ) + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->groupBy("m.description") + ->groupBy("assign_material_to_activity.activity_id") + ->groupBy("assign_material_to_activity.type") + ->where("assign_material_to_activity.activity_id", $id_activity)->get(); + return Datatables::of($data) + ->addIndexColumn() + ->addColumn('qty_sum', function($row){ + $val_qty_act = AssignMaterial::select(ReportActivityMaterial::raw('SUM(ram.qty) as qty_sum'),"m.description as material_name1") + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->join("report_activity_material as ram", "ram.assign_material_id", "=", "assign_material_to_activity.id") + ->groupBy("m.description") + ->where("m.description", strval($row->material_name)) + ->where("ram.activity_id", $row->activity_id)->first(); + return $val_qty_act ? $val_qty_act->qty_sum : '-'; + }) + ->addColumn('status_activity', function($row){ + $val_status = AssignMaterial::select("status_activity") + ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') + ->where('m.description', '=', $row->material_name) + ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); + return $val_status ? $val_status->status_activity : null; + }) + ->addColumn('start_activity', function($row){ + $val_start = AssignMaterial::select("start_activity") + ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') + ->where('m.description', '=', $row->material_name) + ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); + return $val_start ? $val_start->start_activity : null; + }) + ->addColumn('finish_activity', function($row){ + $val_finish = AssignMaterial::select("finish_activity") + ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') + ->where('m.description', '=', $row->material_name) + ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); + return $val_finish ? $val_finish->finish_activity : null; + }) + ->addColumn('uom', function($row){ + $val_uom = RequestMaterial::select("uom") + ->where('description', '=', $row->material_name)->first(); + return $val_uom ? $val_uom->uom : null; + }) + ->addColumn('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){ + $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 .= ''; + return $actionBtn; + }) + ->rawColumns(['action'])->make(true); + } + + public function ForReportActivityByMaterial(Request $request){ + $id_activity = $request->idact; + $data = AssignMaterial::select("assign_material_to_activity.*","m.description as material_name", "m.uom as uom") + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->where('assign_material_to_activity.activity_id', $id_activity)->get(); + foreach ($data as $key) { + $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); + } + } +} diff --git a/app/Http/Controllers/DivisiController.php b/app/Http/Controllers/DivisiController.php index a7d3617..e398682 100644 --- a/app/Http/Controllers/DivisiController.php +++ b/app/Http/Controllers/DivisiController.php @@ -78,7 +78,7 @@ class DivisiController extends Controller } public function search(Request $request) - { + { $payload = $request->all(); $dataBuilder = $this->setUpPayload($payload, 'm_divisi'); $builder = $dataBuilder['builder']; @@ -86,7 +86,8 @@ class DivisiController extends Controller $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() diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index b4cc196..aee3fe3 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use DateTime; use App\Models\Link; use App\Models\User; use App\Models\Image; @@ -366,7 +367,16 @@ class ProjectController extends Controller } public static function setSyncDate($activity_id, $activity, $report) { - $status = AssignMaterial::select('status_activity')->where('activity_id', $activity_id)->first(); + $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'; } @@ -406,7 +416,6 @@ class ProjectController extends Controller $firstReport = ReportActivityMaterial::where('activity_id', $activity_id)->orderBy('report_date')->first(); $reports[] = ProjectController::setSyncDate($activity_id, $activity, $firstReport); } - $activity->reports = $reports; } /* return response()->json(['status'=>'success','data'=> $reports,'code'=>200], 200); */ /* return response()->json(['status'=>'success','data'=> $activities,'code'=>200], 200); */ @@ -429,6 +438,18 @@ class ProjectController extends Controller $activity->save(); } + foreach($activities as $activity) { + $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(); + } + return response()->json(['status'=>'success','message'=>'Synchronize to report success!','code'=>200], 200); } @@ -476,7 +497,7 @@ class ProjectController extends Controller return response()->json(['status' => 'success', 'code' => 200, 'data' => $userProyek, 'totalRecord' => $totalRecord], 200); } - public function detail($id){ + 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); @@ -484,37 +505,49 @@ class ProjectController extends Controller if(!$result) return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); - - $gantt = MasterFunctionsHelper::getLatestGantt($id); + 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'); - $result->header = Activity::whereNull('parent_id')->where("proyek_id", $id)->where("version_gantt_id", $gantt['last_gantt_id'])->first(); - // dd($result->header->start_date); - $ganttId = $gantt['last_gantt_id']; - $actualStartExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_start')->exists(); - $actualEndExist = Activity::where('version_gantt_id', $ganttId)->whereNotNull('actual_end')->exists(); + 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(); + $actualEndExist = Activity::where('proyek_id', $id)->whereNotNull('actual_end')->exists(); + $query = Activity::where('proyek_id', $id); + } 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)->whereNotNull('actual_end')->exists(); + $query = Activity::where('version_gantt_id', $ganttId); + } - if ($actualStartExist) { - $startDate = Activity::where('version_gantt_id', $ganttId) - ->orderBy('actual_start') - ->value('start_date'); - } else { - $startDate = Activity::where('version_gantt_id', $ganttId) - ->orderBy('start_date') - ->value('start_date'); - } - if ($actualEndExist) { - $endDate = Activity::where('version_gantt_id', $ganttId) - ->orderByDesc('actual_end') - ->value('end_date'); - } else { - $endDate = Activity::where('version_gantt_id', $ganttId) - ->orderByDesc('end_date') - ->value('end_date'); - } + if ($actualStartExist) { + $startDate = $query->orderBy('actual_start')->value('start_date'); + } else { + $startDate = $query->orderBy('start_date')->value('start_date'); + } + + if ($actualEndExist) { + $endDate = $query->orderByDesc('actual_end')->value('end_date'); + } else { + $endDate = $query->orderByDesc('end_date')->value('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; - return response()->json(['status'=>'success','code'=> 200,'data'=>$result, 'gantt'=>$gantt], 200); + $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){ diff --git a/app/Http/Controllers/ReportActivityMaterialController.php b/app/Http/Controllers/ReportActivityMaterialController.php index 54be3e0..86cb638 100644 --- a/app/Http/Controllers/ReportActivityMaterialController.php +++ b/app/Http/Controllers/ReportActivityMaterialController.php @@ -59,6 +59,14 @@ class ReportActivityMaterialController extends Controller "updated_by" => $this->currentName ); Activity::where('id', $request->activity_id)->update($dataUpdate); + } else { + $sumAssignMaterial = AssignMaterial::where('activity_id', $request->activity_id)->sum('qty_planning'); + $sumReportActivityMaterial = ReportActivityMaterial::where('activity_id', $request->activity_id)->sum('qty'); + $dataUpdate = array( + "persentase_progress" => $sumReportActivityMaterial/$sumAssignMaterial*100, + "updated_by" => $this->currentName + ); + Activity::where('id', $request->activity_id)->update($dataUpdate); } return response()->json(['status'=>'success','message'=>'Update data status successfully ', 'code'=>200]); @@ -114,12 +122,14 @@ class ReportActivityMaterialController extends Controller ->addIndexColumn() ->addColumn('action', function($row){ $actionBtn = ''; - $actionBtn .= ''; + if ($row->status_activity != 'done') { + $actionBtn .= ''; + } return $actionBtn; }) ->rawColumns(['action'])->make(true); }else{ - $data = ReportActivityMaterial::select("report_activity_material.*", "u.name as human_resource") + $data = ReportActivityMaterial::select("report_activity_material.*", "u.name as human_resource", "amta.status_activity") ->join("assign_material_to_activity as amta", "amta.id", "=", "report_activity_material.assign_material_id") ->join("m_req_material as m", "m.id", "=", "amta.material_id") ->join("m_users as u", "u.id", "=", "report_activity_material.user_id") @@ -131,7 +141,9 @@ class ReportActivityMaterialController extends Controller ->addIndexColumn() ->addColumn('action', function($row){ $actionBtn = ''; - $actionBtn .= ''; + if ($row->status_activity != 'done') { + $actionBtn .= ''; + } return $actionBtn; }) ->rawColumns(['action'])->make(true); diff --git a/app/Http/Controllers/RoleMenuController.php b/app/Http/Controllers/RoleMenuController.php index 05942f5..ebd5d0a 100644 --- a/app/Http/Controllers/RoleMenuController.php +++ b/app/Http/Controllers/RoleMenuController.php @@ -1,102 +1,102 @@ -validate($request, [ - 'role_id' => 'required', - 'menu_id' => 'required', - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = RoleMenu::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'add data role menu successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data role menu failed!','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 = RoleMenu::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data role menu not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data role menu successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data role menu failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = RoleMenu::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data role menu not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data role menu successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data role menu failed deleted!','code'=>400], 400); - } - } - - public function deleteByRole($id) - { - $data = RoleMenu::where("role_id", $id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data role menu not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data role menu successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data role menu failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 't_roles_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); - } -} +validate($request, [ + 'role_id' => 'required', + 'menu_id' => 'required', + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = RoleMenu::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'add data role menu successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add data role menu failed!','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 = RoleMenu::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data role menu not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data role menu successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data role menu failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = RoleMenu::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data role menu not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data role menu successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data role menu failed deleted!','code'=>400], 400); + } + } + + public function deleteByRole($id) + { + $data = RoleMenu::where("role_id", $id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data role menu not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data role menu successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data role menu failed deleted!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 't_roles_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); + } +} diff --git a/app/Models/Activity.php b/app/Models/Activity.php index 3d09785..3a8e54c 100644 --- a/app/Models/Activity.php +++ b/app/Models/Activity.php @@ -1,246 +1,246 @@ -timezone(env('APP_TIMEZONE')) - ->toDateTimeString(); - } - return Carbon::createFromTimestamp(strtotime($value)) - ->timezone(env('APP_TIMEZONE')) - ->toDateTimeString(); - } - - public function getEndDateAttribute($value) - { - if ($value instanceof \DateTime) { - return Carbon::instance($value) - ->timezone(env('APP_TIMEZONE')) - ->toDateTimeString(); - } - return Carbon::createFromTimestamp(strtotime($value)) - ->timezone(env('APP_TIMEZONE')) - ->toDateTimeString(); - } - - - 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(Activity::where("parent_id", $data->parent_id)->count() == 0) - Activity::find($data->parent_id)->update(["type_activity"=>"task"]); - - $data->updateBobot(true); - $data->updateCostPlanning(); - if($data->bobot_planning){ - $data->updatePersentaseProgress(); - } - $data->updateCostActual(); - $data->updateStartEndDateHeader(); - }); - - } - - private function updateBobot($isDelete = false) - { - $root = Activity::where('version_gantt_id', $this->version_gantt_id) - ->where("proyek_id", $this->proyek_id) - ->whereNull('parent_id') - ->first(); - - if($root->rencana_biaya > 0){ - $activities = Activity::where("proyek_id", $this->proyek_id)->where("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->updated_by = auth()->user() ? auth()->user()->name : "system"; - $activity->saveQuietly(); - - } - } else { - if($parent = Activity::find($this->parent_id)){ - $totalChildWeight = Activity::where("parent_id", $this->parent_id)->sum('bobot_planning'); - $parent->update([ - "bobot_planning" => $totalChildWeight - ]); - } - } - } - - private function updateCostActual() - { - $actualCost = Activity::where("parent_id", $this->parent_id)->sum("biaya_actual"); - $this->biaya_actual = $actualCost; - if($parent = Activity::find($this->parent_id)){ - $parent->update([ - "biaya_actual" => $actualCost - ]); - } - } - - private function updatePersentaseProgress() - { - if($parent = Activity::find($this->parent_id)){ - $parentActWeight = $parent->bobot_planning; - - if ($parentActWeight == 0) { - $parent->update([ - "persentase_progress" => 0 - ]); - return; - } - - $totalChildProportionalProgress = 0; - $childs = Activity::where("parent_id", $parent->id)->get(); - foreach($childs as $child){ - $currentActWeight = $child->bobot_planning; - $currentActProportionalProgress = ($currentActWeight / $parentActWeight) * $child->persentase_progress; - $totalChildProportionalProgress += $currentActProportionalProgress; - } - $parent->update([ - "persentase_progress" => $totalChildProportionalProgress - ]); - } - } - - private function updateCostPlanning() { - $sumBiaya = Activity::select(DB::raw('sum(cast(rencana_biaya as double precision))')) - ->where("parent_id", $this->parent_id) - ->first(); - $this->rencana_biaya = $sumBiaya->sum; - if($parent = Activity::find($this->parent_id)){ - $parent->update([ - "rencana_biaya" => $sumBiaya->sum, - ]); - } - } - - private function logPersentaseProgress() - { - ActivityProgressLog::create([ - 'version_gantt_id' => $this->version_gantt_id, - 'activity_id' => request()->id, - 'old_percentage' => $this->persentase_progress, - 'new_percentage' => request()->persentase_progress, - 'variance' => $this->persentase_progress - request()->persentase_progress, - 'created_by'=> "system" - ]); - } - - private function updateStartEndDateHeader() - { - $earliestStartDate = Activity::where('version_gantt_id', $this->version_gantt_id)->whereNotNull('parent_id')->oldest('start_date')->pluck('start_date')->first(); - $latestEndDate = Activity::where('version_gantt_id', $this->version_gantt_id)->whereNotNull('parent_id')->latest('end_date')->pluck('end_date')->first(); - if($header = Activity::where('version_gantt_id', $this->version_gantt_id)->whereNull('parent_id')->first()) { - $header->start_date = $earliestStartDate; - $header->end_date = $latestEndDate; - $header->saveQuietly(); - } - } - - public function getJobsDoneAttribute() - { - if(!ReportActivityMaterial::where('activity_id', $this->id)->first()) - return 0; - if(!$dataPlan = AssignMaterial::where('activity_id', $this->id)->get()) - return 0; - if($dataPlan->isEmpty()) - return 0; - if($dataPlan[0]->status_activity == 'done') - return 100; - return $this->persentase_progress; - } - - public function getAssignHrAttribute() - { - return Arr::flatten(UserToActivity::select("u.name as name") - ->join("m_users as u", "u.id", "=", "assign_hr_to_activity.user_id") - ->where('assign_hr_to_activity.activity_id', $this->id) - ->get() - ->toArray()); - } - - public function getAssignMaterialAttribute() - { - return Arr::flatten(AssignMaterial::select("m.description as name") - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->where('assign_material_to_activity.activity_id', $this->id) - ->where('assign_material_to_activity.type', "material") - ->get() - ->toArray()); - } - - public function getAssignExpenseAttribute() - { - return Arr::flatten(AssignMaterial::select("m.description as name") - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->where('assign_material_to_activity.activity_id', $this->id) - ->where('assign_material_to_activity.type', "expense") - ->get() - ->toArray()); - } - - public function getAssignToolsAttribute() - { - return Arr::flatten(AssignTools::select("m.name as name") - ->join("m_tools_resource as m", "m.id", "=", "assign_tools_to_activity.tools_id") - ->where('assign_tools_to_activity.activity_id', $this->id) - ->get() - ->toArray()); - } - -} +timezone(env('APP_TIMEZONE')) + ->toDateTimeString(); + } + return Carbon::createFromTimestamp(strtotime($value)) + ->timezone(env('APP_TIMEZONE')) + ->toDateTimeString(); + } + + public function getEndDateAttribute($value) + { + if ($value instanceof \DateTime) { + return Carbon::instance($value) + ->timezone(env('APP_TIMEZONE')) + ->toDateTimeString(); + } + return Carbon::createFromTimestamp(strtotime($value)) + ->timezone(env('APP_TIMEZONE')) + ->toDateTimeString(); + } + + + 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(Activity::where("parent_id", $data->parent_id)->count() == 0) + Activity::find($data->parent_id)->update(["type_activity"=>"task"]); + + $data->updateBobot(true); + $data->updateCostPlanning(); + if($data->bobot_planning){ + $data->updatePersentaseProgress(); + } + $data->updateCostActual(); + $data->updateStartEndDateHeader(); + }); + + } + + private function updateBobot($isDelete = false) + { + $root = Activity::where('version_gantt_id', $this->version_gantt_id) + ->where("proyek_id", $this->proyek_id) + ->whereNull('parent_id') + ->first(); + + if($root->rencana_biaya > 0){ + $activities = Activity::where("proyek_id", $this->proyek_id)->where("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->updated_by = auth()->user() ? auth()->user()->name : "system"; + $activity->saveQuietly(); + + } + } else { + if($parent = Activity::find($this->parent_id)){ + $totalChildWeight = Activity::where("parent_id", $this->parent_id)->sum('bobot_planning'); + $parent->update([ + "bobot_planning" => $totalChildWeight + ]); + } + } + } + + private function updateCostActual() + { + $actualCost = Activity::where("parent_id", $this->parent_id)->sum("biaya_actual"); + $this->biaya_actual = $actualCost; + if($parent = Activity::find($this->parent_id)){ + $parent->update([ + "biaya_actual" => $actualCost + ]); + } + } + + private function updatePersentaseProgress() + { + if($parent = Activity::find($this->parent_id)){ + $parentActWeight = $parent->bobot_planning; + + if ($parentActWeight == 0) { + $parent->update([ + "persentase_progress" => 0 + ]); + return; + } + + $totalChildProportionalProgress = 0; + $childs = Activity::where("parent_id", $parent->id)->get(); + foreach($childs as $child){ + $currentActWeight = $child->bobot_planning; + $currentActProportionalProgress = ($currentActWeight / $parentActWeight) * $child->persentase_progress; + $totalChildProportionalProgress += $currentActProportionalProgress; + } + $parent->update([ + "persentase_progress" => $totalChildProportionalProgress + ]); + } + } + + private function updateCostPlanning() { + $sumBiaya = Activity::select(DB::raw('sum(cast(rencana_biaya as double precision))')) + ->where("parent_id", $this->parent_id) + ->first(); + $this->rencana_biaya = $sumBiaya->sum; + if($parent = Activity::find($this->parent_id)){ + $parent->update([ + "rencana_biaya" => $sumBiaya->sum, + ]); + } + } + + private function logPersentaseProgress() + { + ActivityProgressLog::create([ + 'version_gantt_id' => $this->version_gantt_id, + 'activity_id' => request()->id, + 'old_percentage' => $this->persentase_progress, + 'new_percentage' => request()->persentase_progress, + 'variance' => $this->persentase_progress - request()->persentase_progress, + 'created_by'=> "system" + ]); + } + + private function updateStartEndDateHeader() + { + $earliestStartDate = Activity::where('version_gantt_id', $this->version_gantt_id)->whereNotNull('parent_id')->oldest('start_date')->pluck('start_date')->first(); + $latestEndDate = Activity::where('version_gantt_id', $this->version_gantt_id)->whereNotNull('parent_id')->latest('end_date')->pluck('end_date')->first(); + if($header = Activity::where('version_gantt_id', $this->version_gantt_id)->whereNull('parent_id')->first()) { + $header->start_date = $earliestStartDate; + $header->end_date = $latestEndDate; + $header->saveQuietly(); + } + } + + public function getJobsDoneAttribute() + { + if(!ReportActivityMaterial::where('activity_id', $this->id)->first()) + return 0; + if(!$dataPlan = AssignMaterial::where('activity_id', $this->id)->get()) + return 0; + if($dataPlan->isEmpty()) + return 0; + if($dataPlan[0]->status_activity == 'done') + return 100; + return $this->persentase_progress; + } + + public function getAssignHrAttribute() + { + return Arr::flatten(UserToActivity::select("u.name as name") + ->join("m_users as u", "u.id", "=", "assign_hr_to_activity.user_id") + ->where('assign_hr_to_activity.activity_id', $this->id) + ->get() + ->toArray()); + } + + public function getAssignMaterialAttribute() + { + return Arr::flatten(AssignMaterial::select("m.description as name") + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->where('assign_material_to_activity.activity_id', $this->id) + ->where('assign_material_to_activity.type', "material") + ->get() + ->toArray()); + } + + public function getAssignExpenseAttribute() + { + return Arr::flatten(AssignMaterial::select("m.description as name") + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->where('assign_material_to_activity.activity_id', $this->id) + ->where('assign_material_to_activity.type', "expense") + ->get() + ->toArray()); + } + + public function getAssignToolsAttribute() + { + return Arr::flatten(AssignTools::select("m.name as name") + ->join("m_tools_resource as m", "m.id", "=", "assign_tools_to_activity.tools_id") + ->where('assign_tools_to_activity.activity_id', $this->id) + ->get() + ->toArray()); + } + +} diff --git a/app/Models/AssignMaterial.php b/app/Models/AssignMaterial.php index 0c282a6..09620ee 100644 --- a/app/Models/AssignMaterial.php +++ b/app/Models/AssignMaterial.php @@ -1,46 +1,46 @@ - 'integer', - 'budget' => 'string', - ]; - - 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(); - }); - - } -} + 'integer', + 'budget' => 'string', + ]; + + 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(); + }); + + } +} diff --git a/app/Models/ReportActivityMaterial.php b/app/Models/ReportActivityMaterial.php index 44db31c..39849d5 100644 --- a/app/Models/ReportActivityMaterial.php +++ b/app/Models/ReportActivityMaterial.php @@ -1,73 +1,73 @@ -timezone(env('APP_TIMEZONE')) - ->toDateTimeString(); - } - - public static function boot() { - parent::boot(); - - static::created(function($data) { - $activity = Activity::find($data->activity_id); - $assignedMaterial = AssignMaterial::find($data->assign_material_id); - - $biayaActual = $activity->biaya_actual + floatval($assignedMaterial->budget) * floatval($data->qty); - - $dataPlan = AssignMaterial::where('activity_id', $activity->id)->get(); - if($dataPlan[0]->status_activity == 'done'){ - $percentage = 100; - } else { - $totalPlan = $dataPlan->sum('qty_planning'); - $totalVolumeActual = ReportActivityMaterial::where('activity_id', '=', $activity->id)->sum("qty"); - $percentage = ($totalVolumeActual * 100) / $totalPlan; - $percentage = $percentage >= config('app.max_percentage_not_done') ? config('app.max_percentage_not_done') : $percentage; - } - - $activity->update([ - "persentase_progress" => $percentage, - "biaya_actual" => $biayaActual, - ]); - - $activity->save(); - }); - - static::deleted(function($data) { - - $activity = Activity::find($data->activity_id); - $assignedMaterial = AssignMaterial::find($data->assign_material_id); - - $activity->biaya_actual -= floatval($assignedMaterial->budget) * floatval($data->qty); - - $dataPlan = AssignMaterial::where('activity_id', $activity->id)->get(); - $totalPlan = $dataPlan->sum('qty_planning'); - $totalVolumeActual = ReportActivityMaterial::where('activity_id', '=', $activity->id)->sum("qty"); - $percentage = ($totalVolumeActual * 100) / $totalPlan; - $activity->persentase_progress = $percentage >= config('app.max_percentage_not_done') ? config('app.max_percentage_not_done') : $percentage; - $activity->save(); - - }); - - } -} +timezone(env('APP_TIMEZONE')) + ->toDateTimeString(); + } + + public static function boot() { + parent::boot(); + + static::created(function($data) { + $activity = Activity::find($data->activity_id); + $assignedMaterial = AssignMaterial::find($data->assign_material_id); + + $biayaActual = $activity->biaya_actual + floatval($assignedMaterial->budget) * floatval($data->qty); + + $dataPlan = AssignMaterial::where('activity_id', $activity->id)->get(); + if($dataPlan[0]->status_activity == 'done'){ + $percentage = 100; + } else { + $totalPlan = $dataPlan->sum('qty_planning'); + $totalVolumeActual = ReportActivityMaterial::where('activity_id', '=', $activity->id)->sum("qty"); + $percentage = ($totalVolumeActual * 100) / $totalPlan; + $percentage = $percentage >= config('app.max_percentage_not_done') ? config('app.max_percentage_not_done') : $percentage; + } + + $activity->update([ + "persentase_progress" => $percentage, + "biaya_actual" => $biayaActual, + ]); + + $activity->save(); + }); + + static::deleted(function($data) { + + $activity = Activity::find($data->activity_id); + $assignedMaterial = AssignMaterial::find($data->assign_material_id); + + $activity->biaya_actual -= floatval($assignedMaterial->budget) * floatval($data->qty); + + $dataPlan = AssignMaterial::where('activity_id', $activity->id)->get(); + $totalPlan = $dataPlan->sum('qty_planning'); + $totalVolumeActual = ReportActivityMaterial::where('activity_id', '=', $activity->id)->sum("qty"); + $percentage = ($totalVolumeActual * 100) / $totalPlan; + $activity->persentase_progress = $percentage >= config('app.max_percentage_not_done') ? config('app.max_percentage_not_done') : $percentage; + $activity->save(); + + }); + + } +} diff --git a/routes/web.php b/routes/web.php index 376bb43..bcc0e2b 100644 --- a/routes/web.php +++ b/routes/web.php @@ -58,7 +58,7 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->post('/project/add', 'ProjectController@add'); $router->put('/project/update/{id}', 'ProjectController@update'); $router->get('/project/edit/{id}', 'ProjectController@edit'); - $router->get('/project/detail/{id}', 'ProjectController@detail'); + $router->get('/project/detail/{id}[/{gantt_id}[/{s_curve}]]', 'ProjectController@detail'); $router->delete('/project/delete/{id}', 'ProjectController@delete'); $router->get('/project/list', 'ProjectController@list'); $router->get('/project/set-baseline/{gantt_id}', 'ProjectController@setBaseline');