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/BroadcastController.php b/app/Http/Controllers/BroadcastController.php index 87eb02d..66ca433 100644 --- a/app/Http/Controllers/BroadcastController.php +++ b/app/Http/Controllers/BroadcastController.php @@ -1,171 +1,177 @@ -all(); - $data['status_send'] = true; - $data['created_by'] = $this->currentName; - if (isset($data['send_to_id'])) { - $idArray = $data['send_to_id']; - if (is_array($data['send_to_id'])) { - $data['send_to_id'] = implode(", ", $idArray); - } - } - // dd($data); - $result = Broadcast::create($data); - if($result){ - $this->sendNotification($data); - return response()->json(['status'=>'success','message'=>'add broadcast successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add broadcast failed!','code'=>400], 400); - } - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = Broadcast::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data broadcast, please try again later!','code'=>400], 400); - } - } - - public function update(Request $request, $id) - { - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - } - - $data = Broadcast::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data broadcast not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data broadcast successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data broadcast failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = Broadcast::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data broadcast not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data broadcast successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data broadcast failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_broadcast'); - $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 = Broadcast::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list broadcast, please try again later!','code'=>400], 400); - } - } - - public function sendNotification($data) - { - // send_to_type (all, roles, user) - if (isset($data['send_to_type'])) { - switch ($data['send_to_type']) { - case 'all': - $users = User::whereNotNull('fcm_token')->get(); - if (isset($users)) { - foreach ($users as $user) { - FCMService::send( - $user->fcm_token, - [ - 'title' => $data['title_notif'], - 'body' => $data['message_notif'], - ] - ); - } - } - break; - - case 'roles': - $users = User::where("role_id", $data['send_to_id'])->whereNotNull('fcm_token')->get(); - if (isset($users)) { - foreach ($users as $user) { - FCMService::send( - $user->fcm_token, - [ - 'title' => $data['title_notif'], - 'body' => $data['message_notif'], - ] - ); - } - } - break; - - case 'users': - $idArray = explode(", ", $data['send_to_id']); - foreach ($idArray as $key => $value) { - $user = User::where("id", $value)->whereNotNull('fcm_token')->first(); - if (isset($user)) { - FCMService::send( - $user->fcm_token, - [ - 'title' => $data['title_notif'], - 'body' => $data['message_notif'], - ] - ); - } - } - break; - - default: - # code... - break; - } - } - } -} +all(); + $data['created_by'] = $this->currentName; + if (isset($data['send_to_id'])) { + $idArray = $data['send_to_id']; + if (is_array($data['send_to_id'])) { + $data['send_to_id'] = implode(", ", $idArray); + } + } + $result = Broadcast::create($data); + if($result){ + $data['status_send'] !== "registered" ? $this->sendNotification($data) : ''; + return response()->json(['status'=>'success','message'=>'add broadcast successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add broadcast failed!','code'=>400], 400); + } + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = Broadcast::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data broadcast, please try again later!','code'=>400], 400); + } + } + + public function update(Request $request, $id) + { + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + } + + $data = Broadcast::find($id); + + $status_send = $request->status_send; + + if($status_send === 'resend' || $status_send === 'send' && !empty($data)) + { + $data['status_send'] = $status_send; + $this->sendNotification($data); + } + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data broadcast not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data broadcast successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data broadcast failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = Broadcast::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data broadcast not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data broadcast successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data broadcast failed deleted!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_broadcast'); + $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 = Broadcast::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list broadcast, please try again later!','code'=>400], 400); + } + } + + public function sendNotification($data) + { + // send_to_type (all, roles, user) + if (isset($data['send_to_type'])) { + switch ($data['send_to_type']) { + case 'all': + $users = User::whereNotNull('fcm_token')->get(); + if (isset($users)) { + foreach ($users as $user) { + FCMService::send( + $user->fcm_token, + [ + 'title' => $data['title_notif'], + 'body' => $data['message_notif'], + ] + ); + } + } + break; + + case 'roles': + $users = User::where("role_id", $data['send_to_id'])->whereNotNull('fcm_token')->get(); + if (isset($users)) { + foreach ($users as $user) { + FCMService::send( + $user->fcm_token, + [ + 'title' => $data['title_notif'], + 'body' => $data['message_notif'], + ] + ); + } + } + break; + + case 'users': + $idArray = explode(", ", $data['send_to_id']); + foreach ($idArray as $key => $value) { + $user = User::where("id", $value)->whereNotNull('fcm_token')->first(); + if (isset($user)) { + FCMService::send( + $user->fcm_token, + [ + 'title' => $data['title_notif'], + 'body' => $data['message_notif'], + ] + ); + } + } + break; + + default: + # code... + break; + } + } + } +} diff --git a/app/Http/Controllers/DashboardBoDController.php b/app/Http/Controllers/DashboardBoDController.php index 22a53c7..fe2456b 100644 --- a/app/Http/Controllers/DashboardBoDController.php +++ b/app/Http/Controllers/DashboardBoDController.php @@ -271,7 +271,7 @@ class DashboardBoDController extends Controller { $year = $this->interpolateYear($year); - $divisions = Divisi::select('id', 'name') + $divisions = Divisi::select('id', 'name','parent') ->with('children') ->whereNull('parent') ->get(); @@ -358,4 +358,4 @@ class DashboardBoDController extends Controller 'total_manpowers' => User::count() ], 200); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/DivisiController.php b/app/Http/Controllers/DivisiController.php index ea7c3d4..7ef14d3 100644 --- a/app/Http/Controllers/DivisiController.php +++ b/app/Http/Controllers/DivisiController.php @@ -1,99 +1,113 @@ -depth = $depth; - array_push($array, $divisi); - foreach($divisi->children as $child){ - $array = $this->getAllChildren($child, $depth + 1, $array); - } - return $array; - } - - public function add(Request $request){ - $this->validate($request, [ - 'name' => 'required', - 'description' => 'string', - 'parent' => 'integer' - ]); - - $data = $request->all(); - $data['created_by'] = $this->currentName; - - $result = Divisi::create($data); - - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add data','code'=> 500]); - - return response()->json(['status'=>'success','message'=>'Data created!','code'=>200]); - } - - public function update(Request $request, $id){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $data = Divisi::find($id); - - if(!$data) - return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); - - $result = $data->update($request->all()); - - if(!$result) - return response()->json(['status'=>'failed','message'=> 'Update failed!','code'=> 500], 500); - - return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); - } - - public function delete($id) - { - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $data = Divisi::find($id); - - if(!$data) - return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); - - $delete = $data->delete(); - - if(!$delete) - return response()->json(['status'=>'failed','message'=> 'Delete failed!','code'=> 500], 500); - - return response()->json(['status'=>'success','message'=> 'Data deleted!','code'=> 200], 200); - } - - public function search() - { - return $this->list(); - // cant use builder for this case - } - - public function list() - { - $parentMenus = Divisi::whereNull('parent')->with('children')->get(); - $divisions = []; - foreach($parentMenus as $menu){ - $childs = $this->getAllChildren($menu); - foreach($childs as $d){ - $d->displayName = ' ' . $d->name; - for($i=0; $i < $d->depth; $i++){ - $d->displayName = '--' . $d->displayName ; - } - array_push($divisions, $d); - } - } - $countData = count($divisions); - if($countData == 0) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); - - return response()->json(['status'=>'success','code'=>200,'data'=> $divisions, 'totalRecord'=> $countData], 200); - } -} +depth = $depth; + array_push($array, $divisi); + foreach($divisi->children as $child){ + $array = $this->getAllChildren($child, $depth + 1, $array); + } + return $array; + } + + public function add(Request $request){ + $this->validate($request, [ + 'name' => 'string|required|unique:m_divisi,name', + 'description' => 'nullable|string', + 'parent' => 'nullable|integer' + ]); + + $data = $request->all(); + $data['created_by'] = $this->currentName; + + $result = Divisi::create($data); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to add data','code'=> 500]); + + return response()->json(['status'=>'success','message'=>'Data created!','code'=>200]); + } + + public function update(Request $request, $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $this->validate($request, [ + 'name' => 'string|required', + 'description' => 'nullable|string', + 'parent' => 'nullable|integer' + ]); + $data = Divisi::find($id); + + $request->name !== $data['name'] ? $this->validate($request,['name'=>'unique:m_divisi,name']) : ''; + + if(!$data) + return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + + $result = $data->update($request->all()); + + if(!$result) + return response()->json(['status'=>'failed','message'=> 'Update failed!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); + } + + public function delete($id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = Divisi::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + + $delete = $data->delete(); + + if(!$delete) + return response()->json(['status'=>'failed','message'=> 'Delete failed!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=> 'Data deleted!','code'=> 200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_divisi'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + //return $this->list(); + // cant use builder for this case + } + + public function list() + { + $parentMenus = Divisi::with('children')->whereNull('parent')->get(); + $divisions = []; + foreach($parentMenus as $menu){ + $childs = $this->getAllChildren($menu); + foreach($childs as $d){ + $d->displayName = ' ' . $d->name; + for($i=0; $i < $d->depth; $i++){ + $d->displayName = '--' . $d->displayName ; + } + array_push($divisions, $d); + } + } + $countData = count($divisions); + if($countData == 0) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=> $divisions, 'totalRecord'=> $countData], 200); + } +} diff --git a/app/Http/Controllers/HumanResourceController.php b/app/Http/Controllers/HumanResourceController.php index 86f886a..be26a1c 100644 --- a/app/Http/Controllers/HumanResourceController.php +++ b/app/Http/Controllers/HumanResourceController.php @@ -15,7 +15,7 @@ class HumanResourceController extends Controller $this->validate($request, [ 'role_id' => 'required', 'name' => 'required', - 'ktp_number' => 'required', + 'ktp_number' => 'required|numeric|unique:m_users,ktp_number', 'employee_type' => 'required' ]); @@ -56,9 +56,12 @@ class HumanResourceController extends Controller if (!$id || (int) $id < 0 || $id == "") { return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); } - $humanresource = HumanResource::find($id); + $request->ktp_number !== $humanresource['ktp_number'] ? $this->validate($request,['ktp_number'=>'unique:m_users,ktp_number|numeric']) : ''; + $request->email !== $humanresource['email'] ? $this->validate($request,['email'=>'unique:m_users,email|email']) : ''; + $request->password ? $this->validate($request,['password'=>'required|min:8']) : ''; + $data = $request->all(); if (isset($request->password) && $request->password != "") { diff --git a/app/Http/Controllers/MenuController.php b/app/Http/Controllers/MenuController.php index 679c533..6ff9324 100644 --- a/app/Http/Controllers/MenuController.php +++ b/app/Http/Controllers/MenuController.php @@ -1,151 +1,159 @@ -validate($request, [ - 'icon' => 'required', - 'name' => 'required', - 'url' => 'required', - 'sequence' => 'required', - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = Menu::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'add data menu successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data menu failed!','code'=>400], 400); - } - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = Menu::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data menu, please try again later!','code'=>400], 400); - } - } - - 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 = Menu::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data menu successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = Menu::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data menu successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data menu failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_menu'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function listMenu($id) - { - $dataParent = RoleMenu::select("m_menu.*") - ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') - ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') - ->whereNull('m_menu.parent_id') - ->where('m_roles.id', $id) - ->orderBy('m_menu.sequence', 'ASC') - ->get(); - - $finalData = []; - foreach($dataParent as $data){ - $data->children = $this->getChildrenMenu($data->id, $id); - $finalData[] = $data; - } - - return response()->json(['status'=>'success','code'=>200,'data'=>$finalData], 200); - } - - protected function getChildrenMenu($id, $role_id) - { - $dataChildren = RoleMenu::select("m_menu.*") - ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') - ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') - ->where('m_roles.id', $role_id) - ->where('m_menu.parent_id', $id) - ->orderBy('m_menu.sequence', 'ASC') - ->get(); - $children = []; - if($dataChildren){ - foreach($dataChildren as $data) - { - $data->children = $this->getChildrenMenu($data->id, $role_id); - $children[] = $data; - } - } - return $children; - } - - public function list() - { - $data = Menu::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list menu, please try again later!','code'=>400], 400); - } - } -} +validate($request, [ + 'icon' => 'required', + 'name' => 'string|required|unique:m_menu,name', + 'url' => 'required|unique:m_menu,url', + 'sequence' => 'required|integer', + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = Menu::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'add data menu successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add data menu failed!','code'=>400], 400); + } + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = Menu::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data menu, please try again later!','code'=>400], 400); + } + } + + public function update(Request $request, $id) + { + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + } + $this->validate($request, [ + 'icon' => 'required', + 'name' => 'string|required', + 'url' => 'required', + 'sequence' => 'required|integer', + ]); + $data = Menu::find($id); + + $request->name !== $data['name'] ? $this->validate($request,['name'=>'unique:m_menu,name']) : ''; + $request->url !== $data['url'] ? $this->validate($request,['url'=>'unique:m_menu,url']) : ''; + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data menu not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data menu successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data menu failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = Menu::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data menu not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data menu successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data menu failed deleted!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_menu'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function listMenu($id) + { + $dataParent = RoleMenu::select("m_menu.*") + ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') + ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') + ->whereNull('m_menu.parent_id') + ->where('m_roles.id', $id) + ->orderBy('m_menu.sequence', 'ASC') + ->get(); + + $finalData = []; + foreach($dataParent as $data){ + $data->children = $this->getChildrenMenu($data->id, $id); + $finalData[] = $data; + } + + return response()->json(['status'=>'success','code'=>200,'data'=>$finalData], 200); + } + + protected function getChildrenMenu($id, $role_id) + { + $dataChildren = RoleMenu::select("m_menu.*") + ->join('m_menu', 'm_menu.id', '=', 't_roles_menu.menu_id') + ->join('m_roles', 'm_roles.id', '=', 't_roles_menu.role_id') + ->where('m_roles.id', $role_id) + ->where('m_menu.parent_id', $id) + ->orderBy('m_menu.sequence', 'ASC') + ->get(); + $children = []; + if($dataChildren){ + foreach($dataChildren as $data) + { + $data->children = $this->getChildrenMenu($data->id, $role_id); + $children[] = $data; + } + } + return $children; + } + + public function list() + { + $data = Menu::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list menu, please try again later!','code'=>400], 400); + } + } +} diff --git a/app/Http/Controllers/PresenceController.php b/app/Http/Controllers/PresenceController.php index 6aef1a8..0d79917 100644 --- a/app/Http/Controllers/PresenceController.php +++ b/app/Http/Controllers/PresenceController.php @@ -1,619 +1,619 @@ -validate($request, [ - 'user_id' => 'required' - ]); - - $checkLocation = $this->checkLocation($request); - $statusBoundary = false; - $date = date_create($request->clock_time); - // assign and in boundary - if(count($checkLocation) > 0 && $checkLocation[0]['boundary']){ - $statusBoundary = true; - } - $statusRestriction = HumanResource::select('status_boundary')->where('id', $request->user_id)->first(); - if ($statusRestriction->status_boundary) { - $statusBoundary = true; - } - // not assign - if(!$checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ - $data=array( - 'id' => null, - 'boundary' => $statusBoundary - ); - return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda belum di assign ke area kerja.','code'=>200], 200); - } - // assign and not in boundary - if($checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ - $data=array( - 'id' => null, - 'boundary' => true - ); - return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda berada di luar area kerja.','code'=>200], 200); - } - - if($request->type=="out"){ - $clock_out_loc = $this->getLoc($request->clock_out_lat, $request->clock_out_lng)->display_name; - $dataUpdate = array( - "clock_out"=>$request->clock_time, - "clock_out_lat" => $request->clock_out_lat, - "clock_out_lng" => $request->clock_out_lng, - "updated_by"=>$this->currentName, - "clock_out_loc" => $clock_out_loc, - "clock_out_boundary" => $statusBoundary - ); - - $resultUpdate = $this->updateFormAdd($dataUpdate, $request->user_id); - if($resultUpdate && $resultUpdate > 0){ - if($statusBoundary){ - for ($i=0; $i < count($checkLocation); $i++) { - # code... - DB::table('clock_in_out_boundary')->insert([ - "clock_in_out_id" => $resultUpdate, - "user_id" => $request->user_id, - "activity_id" => $checkLocation[$i]['activity_id'], - "type" => $request->type, - "created_at" => $date, - "created_by" => $this->currentName - ]); - }; - }; - $data=array( - 'id' => $resultUpdate, - 'boundary' => $statusBoundary - ); - - return response()->json(['status'=>'success', 'data'=>$data,'message'=>'clock out success!','code'=>200], 200); - } - else{ - return response()->json(['status'=>'failed','message'=>'clock out failed please try again!','code'=>400], 400); - } - die(); - } - - $onlyDate = date_format($date,"Y-m-d"); - $clock_in_loc = $this->getLoc($request->clock_in_lat, $request->clock_in_lng)->display_name; - - $dataAdd = array( - 'user_id'=> $request->user_id, - 'clock_in'=> $request->clock_time, - 'date_presence'=> $onlyDate, - 'created_by' => $this->currentName, - 'clock_in_lat' => $request->clock_in_lat, - 'clock_in_lng' => $request->clock_in_lng, - 'clock_in_loc' => $clock_in_loc, - 'clock_in_boundary' => $statusBoundary - ); - - $result = Presence::create($dataAdd); - $data=array( - 'id' => $result->id, - 'boundary' => $statusBoundary - ); - if($result){ - if($statusBoundary){ - for ($i=0; $i < count($checkLocation); $i++) { - # code... - DB::table('clock_in_out_boundary')->insert([ - "clock_in_out_id" => $result->id, - "user_id" => $request->user_id, - "activity_id" => $checkLocation[$i]['activity_id'], - "type" => $request->type, - "created_at" => $date, - "created_by" => $this->currentName - ]); - }; - }; - return response()->json(['status'=>'success', 'data' => $data,'message'=>'clock in successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'clock in failed!','code'=>400], 400); - } - } - - public function reportK3(Request $request){ - // return response()->json(['status'=>'success', 'message'=>$request->report_k3['detail'],'code'=>200], 200); - - $this->validate($request, [ - 'user_id' => 'required' - ]); - - $checkLocation = $this->checkLocation($request); - $statusBoundary = false; - $date = date_create($request->time); - // assign and in boundary - if(count($checkLocation) > 0 && $checkLocation[0]['boundary']){ - $statusBoundary = true; - } - $statusRestriction = HumanResource::select('status_boundary')->where('id', $request->user_id)->first(); - if ($statusRestriction->status_boundary) { - $statusBoundary = true; - } - // not assign - if(!$checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ - $data=array( - 'id' => null, - 'boundary' => $statusBoundary - ); - return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda belum di assign ke area kerja.','code'=>200], 200); - } - // assign and not in boundary - if($checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ - $data=array( - 'id' => null, - 'boundary' => true - ); - return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda berada di luar area kerja.','code'=>200], 200); - } - - if($request->clock_in_out['type']=="out"){ - $clock_out_loc = $this->getLoc($request->clock_in_out['clock_out_lat'], $request->clock_in_out['clock_out_lng'])->display_name; - $dataUpdate = array( - "clock_out"=>$request->time, - "clock_out_lat" => $request->clock_in_out['clock_out_lat'], - "clock_out_lng" => $request->clock_in_out['clock_out_lng'], - "updated_by"=>$this->currentName, - "clock_out_loc" => $clock_out_loc, - "clock_out_boundary" => $statusBoundary - ); - - $resultUpdate = $this->updateFormAdd($dataUpdate, $request->user_id); - if($resultUpdate && $resultUpdate > 0){ - if($statusBoundary){ - for ($i=0; $i < count($checkLocation); $i++) { - # code... - DB::table('clock_in_out_boundary')->insert([ - "clock_in_out_id" => $resultUpdate, - "user_id" => $request->user_id, - "activity_id" => $checkLocation[$i]['activity_id'], - "type" => $request->clock_in_out['type'], - "created_at" => $date, - "created_by" => $this->currentName - ]); - }; - }; - $data=array( - 'presence_id' => $resultUpdate, - 'boundary' => $statusBoundary - ); - - return response()->json(['status'=>'success', 'data'=>$data,'message'=>'clock out success!','code'=>200], 200); - } - else{ - return response()->json(['status'=>'failed','message'=>'clock out failed please try again!','code'=>400], 400); - } - die(); - } - - $onlyDate = date_format($date,"Y-m-d"); - $clock_in_loc = $this->getLoc($request->clock_in_out['clock_in_lat'], $request->clock_in_out['clock_in_lng'])->display_name; - - $dataFormK3 = array( - "user_id" => $request->user_id, - "proyek_id" => $request->report_k3['proyek_id'], - "report_date" => $request->time, - "description" => $request->report_k3['description'] - ); - - $dataFormPresence = array( - 'user_id' => $request->user_id, - 'clock_in' => $request->time, - 'date_presence' => $onlyDate, - 'created_by' => $this->currentName, - 'clock_in_lat' => $request->clock_in_out['clock_in_lat'], - 'clock_in_lng' => $request->clock_in_out['clock_in_lng'], - 'clock_in_loc' => $clock_in_loc, - 'clock_in_boundary' => $statusBoundary - ); - - $result = Presence::create($dataFormPresence); - $data=array( - 'presence_id' => $result->id, - 'boundary' => $statusBoundary - ); - if($result){ - if($statusBoundary){ - $insertk3 = $this->insertK3($dataFormK3, $request->report_k3['detail']) ; - for ($i=0; $i < count($checkLocation); $i++) { - # code... - DB::table('clock_in_out_boundary')->insert([ - "clock_in_out_id" => $result->id, - "user_id" => $request->user_id, - "activity_id" => $checkLocation[$i]['activity_id'], - "type" => $request->type, - "created_at" => $date, - "created_by" => $this->currentName - ]); - }; - $data['report_id'] = $insertk3->id; - }; - return response()->json(['status'=>'success', 'data'=> $data, 'message'=>'clock in successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'clock in failed!','code'=>400], 400); - } - } - - private function insertK3($params, $details){ - $insert = ReportK3::create($params); - if($insert && $details){ - $this->addDetailK3($details, $insert->id); - } - return $insert; - } - - private function checkLocation($params){ - // cek user tersebut apakah punya assign task yang ada bondary nya - // geom ada di table activity - // $clock_time = - $user = HumanResource::find($params->user_id); - $geom = DB::table("assign_hr_to_activity as ahta")->select("ma.geom", "ma.id") - ->join("m_activity as ma", "ma.id", "=", "ahta.activity_id") - ->where("ahta.user_id", $params->user_id) - ->whereNotNull("ma.geom") - ->whereDate("ma.start_date", "<=", $params->time) - ->whereDate("ma.end_date", ">=", $params->time) - ->get(); - $temp = []; - if (count($geom) > 0) { - foreach($geom as $dataGeom){ - $valGeom = json_decode($dataGeom->geom); - if($params->clock_in_out['type']=="out"){ - if($valGeom->type == "FeatureCollection"){ - $multiArea = $valGeom->features; - foreach($multiArea as $area){ - if ($area->geometry->type === "Point") { - $pointCoordinates = $area->geometry->coordinates; - $pointLng = $pointCoordinates[0]; - $pointLat = $pointCoordinates[1]; - - $check = DB::select(DB::raw("SELECT ST_Distance( - ST_GeomFromGeoJSON('" . json_encode($area->geometry) . "'), - ST_GeomFromText('POINT(" . $params->clock_in_out['clock_in_lng'] . " " . $params->clock_in_out['clock_in_lat'] . ")', 4326) - ) <= " . $area->properties->radius . " as within_radius")); - - if ($check[0]->within_radius) { - break; - } - } - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); - if($check[0]->boundary){ - break; - } - } - }else{ - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); - } - }else{ - if($valGeom->type == "FeatureCollection"){ - $multiArea = $valGeom->features; - foreach($multiArea as $area){ - if ($area->geometry->type === "Point") { - $pointCoordinates = $area->geometry->coordinates; - $pointLng = $pointCoordinates[0]; - $pointLat = $pointCoordinates[1]; - - $check = DB::select(DB::raw("SELECT ST_Distance( - ST_GeomFromGeoJSON('" . json_encode($area->geometry) . "'), - ST_GeomFromText('POINT(" . $params->clock_in_out['clock_in_lng'] . " " . $params->clock_in_out['clock_in_lat'] . ")', 4326) - ) <= " . $area->properties->radius . " as within_radius")); - - if ($check[0]->within_radius) { - break; - } - } - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); - if($check[0]->boundary){ - break; - } - } - }else{ - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); - } - } - if(!$user->status_boundary || count($check)>0){ - if(!$user->status_boundary || (isset($check[0]->boundary) && $check[0]->boundary)){ - $temp[]=array( - "activity_id" => $dataGeom->id, - "boundary" => $check[0]->boundary, - "status_assign" => true - ); - } else if (!$user->status_boundary || (isset($check[0]->within_radius) && $check[0]->within_radius)) { - $temp[]=array( - "activity_id" => $dataGeom->id, - "boundary" => $check[0]->within_radius, - "status_assign" => true - ); - } - } - } - // assign and not in boundary - if(count($temp) < 1){ - $temp[]=array( - "activity_id" => null, - "boundary" => false, - "status_assign" => true - // "geom" => $geom, - // "cek" => $check[0]->boundary - ); - } - } - else{ - // not assign - $temp[]=array( - "activity_id" => null, - "boundary" => false, - "status_assign" => false - ); - } - return $temp; - } - - public function checkLocationTest(Request $request){ - // cek user tersebut apakah punya assign task yang ada bondary nya - // geom ada di table activity - // $clock_time = - $params = $request; - $geom = DB::table("assign_hr_to_activity as ahta")->select("ma.geom", "ma.id") - ->join("m_activity as ma", "ma.id", "=", "ahta.activity_id") - ->where("ahta.user_id", $params->user_id) - ->whereNotNull("ma.geom") - ->whereDate("ma.start_date", "<=", $params->time) - ->whereDate("ma.end_date", ">=", $params->time) - ->get(); - $temp = []; - // return json_encode($geom); - if (count($geom) > 0) { - foreach($geom as $dataGeom){ - $valGeom = json_decode($dataGeom->geom); - if($params->clock_in_out['type']=="out"){ - if($valGeom->type == "FeatureCollection"){ - // return count($valGeom->features); - $multiArea = $valGeom->features; - foreach($multiArea as $area){ - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); - if($check[0]->boundary){ - break; - } - } - }else{ - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); - } - }else{ - if($valGeom->type == "FeatureCollection"){ - // return count($valGeom->features); - $multiArea = $valGeom->features; - foreach($multiArea as $area){ - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); - if($check[0]->boundary){ - break; - } - } - }else{ - $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), - ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); - } - } - if(count($check)>0){ - if($check[0]->boundary){ - $temp[]=array( - "activity_id" => $dataGeom->id, - "boundary" => $check[0]->boundary, - "status_assign" => true - ); - } - } - } - // assign and not in boundary - if(count($temp) < 1){ - $temp[]=array( - "activity_id" => null, - "boundary" => false, - "status_assign" => true - // "geom" => $geom, - // "cek" => $check[0]->boundary - ); - } - } - else{ - // not assign - $temp[]=array( - "activity_id" => null, - "boundary" => false, - "status_assign" => false - ); - } - return $temp; - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = Presence::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data project, please try again later!','code'=>400], 400); - } - } - - public function clockinout($id) { - $dateTimeNow = Carbon::now()->addHour(7); - $dataPresence = Presence::where('user_id', $id)->orderBy('id', 'DESC')->first(); - - if($dataPresence){ - - $dateNow = date("Y-m-d"); - $dateA = strtotime($dataPresence->clock_in); - $dayClockin = date("Y-m-d", $dateA); - if($dayClockin == $dateNow){ - $clock_in = $dataPresence->clock_in; - $clock_out = $dataPresence->clock_out; - }else{ - $clock_in = null; - $clock_out = null; - } - $res_data = array( - "id" => $dataPresence->id, - "at" => $dateTimeNow, - "user_id"=> $id, - "clock_in"=> $clock_in, - "clock_out"=> $clock_out, - "last_clock_in"=> $dataPresence->clock_in, - "last_clock_out"=> $dataPresence->clock_out, - "in_working_time"=> true - ); - return response()->json(['status'=>'success','data'=>$res_data,'code'=>200], 200); - } - $res_data = array( - "id" => null, - "at" => $dateTimeNow, - "user_id"=> $id, - "clock_in"=> null, - "clock_out"=> null, - "last_clock_in"=> null, - "last_clock_out"=> null, - "in_working_time"=> true - ); - return response()->json(['status'=>'success','data'=>$res_data,'code'=>200], 200); - } - - private function updateFormAdd($data, $id){ - $date = date_create($data['clock_out']); - $onlyDate = date_format($date,"Y-m-d"); - - $dataPresence = Presence::where('user_id',$id) - ->where("clock_in", "<=", $data["clock_out"]) - ->orderByDesc("id") - ->first(); - - if($dataPresence){ - $queryUpdate = $dataPresence->update($data); - if($queryUpdate){ - $getDataUpdate = Presence::where('user_id', $id)->where("date_presence", $onlyDate)->first(); - return $getDataUpdate->id; - }else{ - return false; - } - }else{ - return false; - } - die(); - } - - 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 = Presence::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data presence not found!','code'=>400], 400); - die(); - } - - if($result){ - return response()->json(['status'=>'success','message'=>'data presence successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data presence failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = Presence::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data presence not found!','code'=>400], 400); - die(); - } - - if($delete){ - return response()->json(['status'=>'success','message'=>'data presence successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data presence failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 't_clock_in_out'); - $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 = Presence::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list presence, please try again later!','code'=>400], 400); - } - } - - public function bulkUpdateLocation() - { - $data = Presence::all(); - $finalData = []; - foreach($data as $objRow) { - $presence = Presence::find($objRow->id); - - $clock_in_lat = $objRow->clock_in_lat; - $clock_in_lng = $objRow->clock_in_lng; - $objRow->clock_in_loc = ""; - if (isset($clock_in_lat) && isset($clock_in_lng)) { - $objRow->clock_in_loc = $this->getLoc($clock_in_lat, $clock_in_lng)->display_name; - } - - $clock_out_lat = $objRow->clock_out_lat; - $clock_out_lng = $objRow->clock_out_lng; - $objRow->clock_out_loc = ""; - if (isset($clock_out_lat) && isset($clock_out_lng) && $clock_out_lng != null) { - $locAddress = $this->getLoc($clock_out_lat, $clock_out_lng); - $objRow->clock_out_loc = isset($locAddress->display_name) ? $locAddress->display_name : "-"; - } - - - $presence->clock_in_loc = $objRow->clock_in_loc; - $presence->clock_out_loc = $objRow->clock_out_loc; - $presence->save(); - } - return response()->json(['status'=>'success','message'=>'success update!','code'=>200], 200); - } -} +validate($request, [ + 'user_id' => 'required' + ]); + + $checkLocation = $this->checkLocation($request); + $statusBoundary = false; + $date = date_create($request->clock_time); + // assign and in boundary + if(count($checkLocation) > 0 && $checkLocation[0]['boundary']){ + $statusBoundary = true; + } + $statusRestriction = HumanResource::select('status_boundary')->where('id', $request->user_id)->first(); + if ($statusRestriction->status_boundary) { + $statusBoundary = true; + } + // not assign + if(!$checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ + $data=array( + 'id' => null, + 'boundary' => $statusBoundary + ); + return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda belum di assign ke area kerja.','code'=>200], 200); + } + // assign and not in boundary + if($checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ + $data=array( + 'id' => null, + 'boundary' => true + ); + return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda berada di luar area kerja.','code'=>200], 200); + } + + if($request->type=="out"){ + $clock_out_loc = $this->getLoc($request->clock_out_lat, $request->clock_out_lng)->display_name; + $dataUpdate = array( + "clock_out"=>$request->clock_time, + "clock_out_lat" => $request->clock_out_lat, + "clock_out_lng" => $request->clock_out_lng, + "updated_by"=>$this->currentName, + "clock_out_loc" => $clock_out_loc, + "clock_out_boundary" => $statusBoundary + ); + + $resultUpdate = $this->updateFormAdd($dataUpdate, $request->user_id); + if($resultUpdate && $resultUpdate > 0){ + if($statusBoundary){ + for ($i=0; $i < count($checkLocation); $i++) { + # code... + DB::table('clock_in_out_boundary')->insert([ + "clock_in_out_id" => $resultUpdate, + "user_id" => $request->user_id, + "activity_id" => $checkLocation[$i]['activity_id'], + "type" => $request->type, + "created_at" => $date, + "created_by" => $this->currentName + ]); + }; + }; + $data=array( + 'id' => $resultUpdate, + 'boundary' => $statusBoundary + ); + + return response()->json(['status'=>'success', 'data'=>$data,'message'=>'clock out success!','code'=>200], 200); + } + else{ + return response()->json(['status'=>'failed','message'=>'clock out failed please try again!','code'=>400], 400); + } + die(); + } + + $onlyDate = date_format($date,"Y-m-d"); + $clock_in_loc = $this->getLoc($request->clock_in_lat, $request->clock_in_lng)->display_name; + + $dataAdd = array( + 'user_id'=> $request->user_id, + 'clock_in'=> $request->clock_time, + 'date_presence'=> $onlyDate, + 'created_by' => $this->currentName, + 'clock_in_lat' => $request->clock_in_lat, + 'clock_in_lng' => $request->clock_in_lng, + 'clock_in_loc' => $clock_in_loc, + 'clock_in_boundary' => $statusBoundary + ); + + $result = Presence::create($dataAdd); + $data=array( + 'id' => $result->id, + 'boundary' => $statusBoundary + ); + if($result){ + if($statusBoundary){ + for ($i=0; $i < count($checkLocation); $i++) { + # code... + DB::table('clock_in_out_boundary')->insert([ + "clock_in_out_id" => $result->id, + "user_id" => $request->user_id, + "activity_id" => $checkLocation[$i]['activity_id'], + "type" => $request->type, + "created_at" => $date, + "created_by" => $this->currentName + ]); + }; + }; + return response()->json(['status'=>'success', 'data' => $data,'message'=>'clock in successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'clock in failed!','code'=>400], 400); + } + } + + public function reportK3(Request $request){ + // return response()->json(['status'=>'success', 'message'=>$request->report_k3['detail'],'code'=>200], 200); + + $this->validate($request, [ + 'user_id' => 'required' + ]); + + $checkLocation = $this->checkLocation($request); + $statusBoundary = false; + $date = date_create($request->time); + // assign and in boundary + if(count($checkLocation) > 0 && $checkLocation[0]['boundary']){ + $statusBoundary = true; + } + $statusRestriction = HumanResource::select('status_boundary')->where('id', $request->user_id)->first(); + if ($statusRestriction->status_boundary) { + $statusBoundary = true; + } + // not assign + if(!$checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ + $data=array( + 'id' => null, + 'boundary' => $statusBoundary + ); + return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda belum di assign ke area kerja.','code'=>200], 200); + } + // assign and not in boundary + if($checkLocation[0]['status_assign'] && $checkLocation[0]['boundary'] == false){ + $data=array( + 'id' => null, + 'boundary' => true + ); + return response()->json(['status'=>'failed', 'data'=>$data, 'message'=>'Tidak dapat melakukan presensi. Anda berada di luar area kerja.','code'=>200], 200); + } + + if($request->clock_in_out['type']=="out"){ + $clock_out_loc = $this->getLoc($request->clock_in_out['clock_out_lat'], $request->clock_in_out['clock_out_lng'])->display_name; + $dataUpdate = array( + "clock_out"=>$request->time, + "clock_out_lat" => $request->clock_in_out['clock_out_lat'], + "clock_out_lng" => $request->clock_in_out['clock_out_lng'], + "updated_by"=>$this->currentName, + "clock_out_loc" => $clock_out_loc, + "clock_out_boundary" => $statusBoundary + ); + + $resultUpdate = $this->updateFormAdd($dataUpdate, $request->user_id); + if($resultUpdate && $resultUpdate > 0){ + if($statusBoundary){ + for ($i=0; $i < count($checkLocation); $i++) { + # code... + DB::table('clock_in_out_boundary')->insert([ + "clock_in_out_id" => $resultUpdate, + "user_id" => $request->user_id, + "activity_id" => $checkLocation[$i]['activity_id'], + "type" => $request->clock_in_out['type'], + "created_at" => $date, + "created_by" => $this->currentName + ]); + }; + }; + $data=array( + 'presence_id' => $resultUpdate, + 'boundary' => $statusBoundary + ); + + return response()->json(['status'=>'success', 'data'=>$data,'message'=>'clock out success!','code'=>200], 200); + } + else{ + return response()->json(['status'=>'failed','message'=>'clock out failed please try again!','code'=>400], 400); + } + die(); + } + + $onlyDate = date_format($date,"Y-m-d"); + $clock_in_loc = $this->getLoc($request->clock_in_out['clock_in_lat'], $request->clock_in_out['clock_in_lng'])->display_name; + + $dataFormK3 = array( + "user_id" => $request->user_id, + "proyek_id" => $request->report_k3['proyek_id'], + "report_date" => $request->time, + "description" => $request->report_k3['description'] + ); + + $dataFormPresence = array( + 'user_id' => $request->user_id, + 'clock_in' => $request->time, + 'date_presence' => $onlyDate, + 'created_by' => $this->currentName, + 'clock_in_lat' => $request->clock_in_out['clock_in_lat'], + 'clock_in_lng' => $request->clock_in_out['clock_in_lng'], + 'clock_in_loc' => $clock_in_loc, + 'clock_in_boundary' => $statusBoundary + ); + + $result = Presence::create($dataFormPresence); + $data=array( + 'presence_id' => $result->id, + 'boundary' => $statusBoundary + ); + if($result){ + if($statusBoundary){ + $insertk3 = $this->insertK3($dataFormK3, $request->report_k3['detail']) ; + for ($i=0; $i < count($checkLocation); $i++) { + # code... + DB::table('clock_in_out_boundary')->insert([ + "clock_in_out_id" => $result->id, + "user_id" => $request->user_id, + "activity_id" => $checkLocation[$i]['activity_id'], + "type" => $request->type, + "created_at" => $date, + "created_by" => $this->currentName + ]); + }; + $data['report_id'] = $insertk3->id; + }; + return response()->json(['status'=>'success', 'data'=> $data, 'message'=>'clock in successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'clock in failed!','code'=>400], 400); + } + } + + private function insertK3($params, $details){ + $insert = ReportK3::create($params); + if($insert && $details){ + $this->addDetailK3($details, $insert->id); + } + return $insert; + } + + private function checkLocation($params){ + // cek user tersebut apakah punya assign task yang ada bondary nya + // geom ada di table activity + // $clock_time = + $user = HumanResource::find($params->user_id); + $geom = DB::table("assign_hr_to_activity as ahta")->select("ma.geom", "ma.id") + ->join("m_activity as ma", "ma.id", "=", "ahta.activity_id") + ->where("ahta.user_id", $params->user_id) + ->whereNotNull("ma.geom") + ->whereDate("ma.start_date", "<=", $params->time) + ->whereDate("ma.end_date", ">=", $params->time) + ->get(); + $temp = []; + if (count($geom) > 0) { + foreach($geom as $dataGeom){ + $valGeom = json_decode($dataGeom->geom); + if($params->clock_in_out['type']=="out"){ + if($valGeom->type == "FeatureCollection"){ + $multiArea = $valGeom->features; + foreach($multiArea as $area){ + if ($area->geometry->type === "Point") { + $pointCoordinates = $area->geometry->coordinates; + $pointLng = $pointCoordinates[0]; + $pointLat = $pointCoordinates[1]; + + $check = DB::select(DB::raw("SELECT ST_Distance( + ST_GeomFromGeoJSON('" . json_encode($area->geometry) . "'), + ST_GeomFromText('POINT(" . $params->clock_in_out['clock_in_lng'] . " " . $params->clock_in_out['clock_in_lat'] . ")', 4326) + ) <= " . $area->properties->radius . " as within_radius")); + + if ($check[0]->within_radius) { + break; + } + } + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); + if($check[0]->boundary){ + break; + } + } + }else{ + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); + } + }else{ + if($valGeom->type == "FeatureCollection"){ + $multiArea = $valGeom->features; + foreach($multiArea as $area){ + if ($area->geometry->type === "Point") { + $pointCoordinates = $area->geometry->coordinates; + $pointLng = $pointCoordinates[0]; + $pointLat = $pointCoordinates[1]; + + $check = DB::select(DB::raw("SELECT ST_Distance( + ST_GeomFromGeoJSON('" . json_encode($area->geometry) . "'), + ST_GeomFromText('POINT(" . $params->clock_in_out['clock_in_lng'] . " " . $params->clock_in_out['clock_in_lat'] . ")', 4326) + ) <= " . $area->properties->radius . " as within_radius")); + + if ($check[0]->within_radius) { + break; + } + } + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); + if($check[0]->boundary){ + break; + } + } + }else{ + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); + } + } + if(!$user->status_boundary || count($check)>0){ + if(!$user->status_boundary || (isset($check[0]->boundary) && $check[0]->boundary)){ + $temp[]=array( + "activity_id" => $dataGeom->id, + "boundary" => $check[0]->boundary, + "status_assign" => true + ); + } else if (!$user->status_boundary || (isset($check[0]->within_radius) && $check[0]->within_radius)) { + $temp[]=array( + "activity_id" => $dataGeom->id, + "boundary" => $check[0]->within_radius, + "status_assign" => true + ); + } + } + } + // assign and not in boundary + if(count($temp) < 1){ + $temp[]=array( + "activity_id" => null, + "boundary" => false, + "status_assign" => true + // "geom" => $geom, + // "cek" => $check[0]->boundary + ); + } + } + else{ + // not assign + $temp[]=array( + "activity_id" => null, + "boundary" => false, + "status_assign" => false + ); + } + return $temp; + } + + public function checkLocationTest(Request $request){ + // cek user tersebut apakah punya assign task yang ada bondary nya + // geom ada di table activity + // $clock_time = + $params = $request; + $geom = DB::table("assign_hr_to_activity as ahta")->select("ma.geom", "ma.id") + ->join("m_activity as ma", "ma.id", "=", "ahta.activity_id") + ->where("ahta.user_id", $params->user_id) + ->whereNotNull("ma.geom") + ->whereDate("ma.start_date", "<=", $params->time) + ->whereDate("ma.end_date", ">=", $params->time) + ->get(); + $temp = []; + // return json_encode($geom); + if (count($geom) > 0) { + foreach($geom as $dataGeom){ + $valGeom = json_decode($dataGeom->geom); + if($params->clock_in_out['type']=="out"){ + if($valGeom->type == "FeatureCollection"){ + // return count($valGeom->features); + $multiArea = $valGeom->features; + foreach($multiArea as $area){ + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); + if($check[0]->boundary){ + break; + } + } + }else{ + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_out_lng']." ".$params->clock_in_out['clock_out_lat'].")', 4326)) as boundary")); + } + }else{ + if($valGeom->type == "FeatureCollection"){ + // return count($valGeom->features); + $multiArea = $valGeom->features; + foreach($multiArea as $area){ + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($area->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); + if($check[0]->boundary){ + break; + } + } + }else{ + $check = DB::select(DB::raw("SELECT ST_Intersects(ST_GeomFromGeoJSON('".json_encode($valGeom->geometry)."'), + ST_GeomFromText('POINT(".$params->clock_in_out['clock_in_lng']." ".$params->clock_in_out['clock_in_lat'].")', 4326)) as boundary")); + } + } + if(count($check)>0){ + if($check[0]->boundary){ + $temp[]=array( + "activity_id" => $dataGeom->id, + "boundary" => $check[0]->boundary, + "status_assign" => true + ); + } + } + } + // assign and not in boundary + if(count($temp) < 1){ + $temp[]=array( + "activity_id" => null, + "boundary" => false, + "status_assign" => true + // "geom" => $geom, + // "cek" => $check[0]->boundary + ); + } + } + else{ + // not assign + $temp[]=array( + "activity_id" => null, + "boundary" => false, + "status_assign" => false + ); + } + return $temp; + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = Presence::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data project, please try again later!','code'=>400], 400); + } + } + + public function clockinout($id) { + $dateTimeNow = Carbon::now()->addHour(7); + $dataPresence = Presence::where('user_id', $id)->orderBy('id', 'DESC')->first(); + + if($dataPresence){ + + $dateNow = date("Y-m-d"); + $dateA = strtotime($dataPresence->clock_in); + $dayClockin = date("Y-m-d", $dateA); + if($dayClockin == $dateNow){ + $clock_in = $dataPresence->clock_in; + $clock_out = $dataPresence->clock_out; + }else{ + $clock_in = null; + $clock_out = null; + } + $res_data = array( + "id" => $dataPresence->id, + "at" => $dateTimeNow, + "user_id"=> $id, + "clock_in"=> $clock_in, + "clock_out"=> $clock_out, + "last_clock_in"=> $dataPresence->clock_in, + "last_clock_out"=> $dataPresence->clock_out, + "in_working_time"=> true + ); + return response()->json(['status'=>'success','data'=>$res_data,'code'=>200], 200); + } + $res_data = array( + "id" => null, + "at" => $dateTimeNow, + "user_id"=> $id, + "clock_in"=> null, + "clock_out"=> null, + "last_clock_in"=> null, + "last_clock_out"=> null, + "in_working_time"=> true + ); + return response()->json(['status'=>'success','data'=>$res_data,'code'=>200], 200); + } + + private function updateFormAdd($data, $id){ + $date = date_create($data['clock_out']); + $onlyDate = date_format($date,"Y-m-d"); + + $dataPresence = Presence::where('user_id',$id) + ->where("clock_in", "<=", $data["clock_out"]) + ->orderByDesc("id") + ->first(); + + if($dataPresence){ + $queryUpdate = $dataPresence->update($data); + if($queryUpdate){ + $getDataUpdate = Presence::where('user_id', $id)->where("date_presence", $onlyDate)->first(); + return $getDataUpdate->id; + }else{ + return false; + } + }else{ + return false; + } + die(); + } + + 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 = Presence::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data presence not found!','code'=>400], 400); + die(); + } + + if($result){ + return response()->json(['status'=>'success','message'=>'data presence successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data presence failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = Presence::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data presence not found!','code'=>400], 400); + die(); + } + + if($delete){ + return response()->json(['status'=>'success','message'=>'data presence successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data presence failed deleted!','code'=>400], 400); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 't_clock_in_out'); + $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 = Presence::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list presence, please try again later!','code'=>400], 400); + } + } + + public function bulkUpdateLocation() + { + $data = Presence::all(); + $finalData = []; + foreach($data as $objRow) { + $presence = Presence::find($objRow->id); + + $clock_in_lat = $objRow->clock_in_lat; + $clock_in_lng = $objRow->clock_in_lng; + $objRow->clock_in_loc = ""; + if (isset($clock_in_lat) && isset($clock_in_lng)) { + $objRow->clock_in_loc = $this->getLoc($clock_in_lat, $clock_in_lng)->display_name; + } + + $clock_out_lat = $objRow->clock_out_lat; + $clock_out_lng = $objRow->clock_out_lng; + $objRow->clock_out_loc = ""; + if (isset($clock_out_lat) && isset($clock_out_lng) && $clock_out_lng != null) { + $locAddress = $this->getLoc($clock_out_lat, $clock_out_lng); + $objRow->clock_out_loc = isset($locAddress->display_name) ? $locAddress->display_name : "-"; + } + + + $presence->clock_in_loc = $objRow->clock_in_loc; + $presence->clock_out_loc = $objRow->clock_out_loc; + $presence->save(); + } + return response()->json(['status'=>'success','message'=>'success update!','code'=>200], 200); + } +} diff --git a/app/Http/Controllers/ProjectChecklistsController.php b/app/Http/Controllers/ProjectChecklistsController.php new file mode 100644 index 0000000..c7e0590 --- /dev/null +++ b/app/Http/Controllers/ProjectChecklistsController.php @@ -0,0 +1,136 @@ +status_exist==="") { + $request->merge(['status_exist' => true]); + } + + $this->validate($request, [ + 'proyek_id' => 'required', + 'item' => 'required|string', + 'status_exist' => 'boolean' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = ProjectChecklists::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'add data project participants successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add data project participants failed!','code'=>400], 400); + } + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = ProjectChecklists::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data project participants, please try again later!','code'=>400], 400); + } + } + + public function update(Request $request, $id) + { + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + } + + $data = ProjectChecklists::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data project participants successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = ProjectChecklists::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data project participants successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants failed deleted!','code'=>400], 400); + } + } + + public function deleteByProyek($id) + { + $data = ProjectChecklists::where('proyek_id', $id)->delete(); + + if($data){ + return response()->json(['status'=>'success','message'=>'data project participants successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'success','message'=>'data project participants failed deleted, because data not found!','code'=>200], 200); + } + } + + public function customWhere($where, $val) + { + $data = ProjectChecklists::where($where, $val)->orderBy('id', 'asc')->get(); + + if($data){ + return response()->json(['status'=>'success','data'=> $data,'code'=>200], 200); + }else{ + return response()->json(['status'=>'success','message'=>'data project participants not found!','code'=>400], 40); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'project_charter_checklist'); + $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 = ProjectChecklists::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list project participants, please try again later!','code'=>400], 400); + } + } +} diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 5e0fbde..aee3fe3 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -2,35 +2,39 @@ namespace App\Http\Controllers; -use Illuminate\Http\Request; +use DateTime; +use App\Models\Link; +use App\Models\User; +use App\Models\Image; +use App\Models\Holiday; use App\Models\Project; -use App\Models\UserToProyek; use App\Models\Activity; -use App\Models\UserToActivity; -use App\Models\User; +use App\Jobs\ProcessSCurve; +use App\Models\OfficeHours; +use App\Models\ProjectType; +use App\Models\ProjectPhase; +use App\Models\UserToProyek; +use App\Models\VersionGantt; +use Illuminate\Http\Request; +use App\Models\ProjectIssues; use App\Models\AssignMaterial; use App\Models\DokumenProject; -use App\Models\FolderDocumentProyek; use App\Models\ProjectCharter; -use App\Models\ProjectApproval; -use App\Models\ProjectPhase; -use App\Models\ProjectType; -use App\Models\ProjectMileStone; -use App\Models\ProjectParticipants; +use App\Models\ReportActivity; use App\Models\ShowHideColumn; -use App\Models\VersionGantt; -use App\Models\Image; -use App\Models\CommentActivity; -use App\Models\Link; +use App\Models\UserToActivity; use App\Models\ActivityDokumen; -use App\Models\Holiday; -use App\Models\ReportActivity; -use App\Models\OfficeHours; +use App\Models\CommentActivity; +use App\Models\ProjectApproval; +use App\Models\ProjectMileStone; +use App\Models\ProjectChecklists; use Illuminate\Support\Facades\DB; +use App\Models\ProjectParticipants; +use App\Models\FolderDocumentProyek; use App\Helpers\MasterFunctionsHelper; +use App\Models\ProjectRisks; use App\Models\ReportActivityMaterial; use Illuminate\Support\Facades\Artisan; -use App\Jobs\ProcessSCurve; const API_GEOLOCATION = "https://nominatim.oslogdev.com/search/ADDR?format=json&addressdetails=1&limit=1"; @@ -65,11 +69,22 @@ class ProjectController extends Controller return response()->json(['status'=>'success','message'=>'Data added!', 'data_result' =>$dataResultInsert, 'code'=> 200], 200); } - public function edit($id){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + public function edit($id) + { + if (empty($id) || !is_int((int)$id)) + return response()->json(['status' => 'failed', 'message' => 'id is required!', 'code' => 400], 400); - $result = Project::find($id); + $result = Project::query() + ->from('m_proyek AS mp') + ->where('mp.id', $id) + ->selectRaw('kode_sortname,jumlah_stakeholder,nama,mulai_proyek,akhir_proyek,area_kerja,lokasi_kantor,rencana_biaya,biaya_actual,company,pm_id,type_proyek_id,divisi_id,persentase_progress,keterangan,durasi_proyek,progress_by_worklog,currency_symbol,late_consequence,assumtion,currency_code,currency_name,project_objectives,considered_success_when,potential_risk,testing_environment,budget_health,phase_id,calculation_status'); + + if (!is_null($result->first()['divisi_id'])) { + $result->leftJoin('m_divisi', 'mp.divisi_id', '=', 'm_divisi.id') + ->addSelect(DB::raw('m_divisi.name AS nama_divisi')); + } + + $result = $result->first(); if(!$result) return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); @@ -145,6 +160,9 @@ class ProjectController extends Controller ProjectApproval::where('proyek_id', $project_id)->delete(); ProjectMileStone::where('proyek_id', $project_id)->delete(); ProjectParticipants::where('proyek_id', $project_id)->delete(); + ProjectChecklists::where('proyek_id', $project_id)->delete(); + ProjectIssues::where('proyek_id', $project_id)->delete(); + ProjectRisks::where('proyek_id', $project_id)->delete(); $this->deleteVersionGantt($project_id); $this->deleteDokumenProject($project_id); } @@ -349,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'; } @@ -389,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); */ @@ -412,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); } @@ -459,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); @@ -467,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 = $query->orderBy('actual_start')->value('start_date'); + } else { + $startDate = $query->orderBy('start_date')->value('start_date'); + } - 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 ($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/ProjectIssuesController.php b/app/Http/Controllers/ProjectIssuesController.php new file mode 100644 index 0000000..fc54850 --- /dev/null +++ b/app/Http/Controllers/ProjectIssuesController.php @@ -0,0 +1,136 @@ +level_issue === "") { + $request->merge(['level_issue' => 0]); + } + + $this->validate($request, [ + 'proyek_id' => 'required', + 'description' => 'required|string', + 'level_issue' => 'required|integer' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = ProjectIssues::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'add data project participants successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add data project participants failed!','code'=>400], 400); + } + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = ProjectIssues::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data project participants, please try again later!','code'=>400], 400); + } + } + + public function update(Request $request, $id) + { + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + } + + $data = ProjectIssues::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data project participants successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = ProjectIssues::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data project participants successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants failed deleted!','code'=>400], 400); + } + } + + public function deleteByProyek($id) + { + $data = ProjectIssues::where('proyek_id', $id)->delete(); + + if($data){ + return response()->json(['status'=>'success','message'=>'data project participants successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'success','message'=>'data project participants failed deleted, because data not found!','code'=>200], 200); + } + } + + public function customWhere($where, $val) + { + $data = ProjectIssues::where($where, $val)->orderBy('id', 'asc')->get(); + + if($data){ + return response()->json(['status'=>'success','data'=> $data,'code'=>200], 200); + }else{ + return response()->json(['status'=>'success','message'=>'data project participants not found!','code'=>400], 40); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'project_charter_issue'); + $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 = ProjectIssues::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list project participants, please try again later!','code'=>400], 400); + } + } +} diff --git a/app/Http/Controllers/ProjectRisksController.php b/app/Http/Controllers/ProjectRisksController.php new file mode 100644 index 0000000..d5c53df --- /dev/null +++ b/app/Http/Controllers/ProjectRisksController.php @@ -0,0 +1,137 @@ +level_risk === "") { + $request->merge(['level_risk' => 0]); + } + + $this->validate($request, [ + 'proyek_id' => 'required', + 'level_risk' => 'required|integer', + 'description' => 'required|string', + 'preventive_risk' => 'required|string' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = ProjectRisks::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'add data project participants successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add data project participants failed!','code'=>400], 400); + } + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = ProjectRisks::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data project participants, please try again later!','code'=>400], 400); + } + } + + public function update(Request $request, $id) + { + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + } + + $data = ProjectRisks::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data project participants successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = ProjectRisks::find($id); + + if($data){ + $delete = $data->delete(); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data project participants successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data project participants failed deleted!','code'=>400], 400); + } + } + + public function deleteByProyek($id) + { + $data = ProjectRisks::where('proyek_id', $id)->delete(); + + if($data){ + return response()->json(['status'=>'success','message'=>'data project participants successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'success','message'=>'data project participants failed deleted, because data not found!','code'=>200], 200); + } + } + + public function customWhere($where, $val) + { + $data = ProjectRisks::where($where, $val)->orderBy('id', 'asc')->get(); + + if($data){ + return response()->json(['status'=>'success','data'=> $data,'code'=>200], 200); + }else{ + return response()->json(['status'=>'success','message'=>'data project participants not found!','code'=>400], 40); + } + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'project_charter_risk'); + $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 = ProjectRisks::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list project participants, please try again later!','code'=>400], 400); + } + } +} 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/RoleController.php b/app/Http/Controllers/RoleController.php index b420107..4a29066 100644 --- a/app/Http/Controllers/RoleController.php +++ b/app/Http/Controllers/RoleController.php @@ -1,101 +1,106 @@ -validate($request, [ - 'name' => 'required', - 'description' => 'required' - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = Role::create($data); - - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=>500], 500); - - return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); - } - - public function edit( $id){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $result = Role::find($id); - - if(!$result) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); - - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - } - - public function update(Request $request, $id) - { - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $data = Role::find($id); - - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); - - $result = $data->update($request->all()); - - if(!$result) - return response()->json(['status'=>'failed','message'=>'Failed to update the data!','code'=>500], 500); - - return response()->json(['status'=>'success','message'=>'Data updated!','code'=>200], 200); - } - - public function delete($id) - { - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $data = Role::find($id); - - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); - - $delete = $data->delete(); - - if(!$delete) - return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=>500], 500); - - return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); - } - - public function search(Request $request) - { - $payload = $request->all(); - - $dataBuilder = $this->setUpPayload($payload, 'm_roles'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = Role::all(); - $countData = $data->count(); - - if(!$data) - return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); - - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - } -} +validate($request, [ + 'name' => 'string|required|unique:m_roles,name', + 'description' => 'required' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = Role::create($data); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=>500], 500); + + return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); + } + + public function edit( $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $result = Role::find($id); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + } + + public function update(Request $request, $id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $this->validate($request, [ + 'name' => 'string|required', + 'description' => 'required' + ]); + $data = Role::find($id); + $request->name !== $data['name'] ? $this->validate($request,['name'=>'unique:m_roles,name']) : ''; + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + + $result = $data->update($request->all()); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to update the data!','code'=>500], 500); + + return response()->json(['status'=>'success','message'=>'Data updated!','code'=>200], 200); + } + + public function delete($id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = Role::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + + $delete = $data->delete(); + + if(!$delete) + return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=>500], 500); + + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + + $dataBuilder = $this->setUpPayload($payload, 'm_roles'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = Role::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + } +} 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/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index 14e67ed..5951aa6 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -1,199 +1,220 @@ -validate($request, [ - 'activity_id' => 'required', - 'user_id' => 'required' - ]); - - $data = $request->all(); - $data['created_by'] = $this->currentName; - - if(!UserToActivity::create($data)) - return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500]); - - return response()->json(['status'=>'success','message'=>'Data added!', 'code'=> 200]); - } - - public function addMultiple(Request $request){ - $users_id = $request->user_id; - $users_role = $request->role_proyek_id; - - // $data = UserToActivity::where("activity_id", $request->activity_id); - // if($data){ - // $data->delete(); - // } - - if(is_array($users_id) && count($users_id) > 0){ - $countRes = 0; - foreach($users_id as $index => $item){ - $dataInsert = array( - "user_id" => $item, - "activity_id" => $request->activity_id, - "role_proyek_id" => $users_role[$index], - "proyek_id" => $request->proyek_id, - "created_by" => $this->currentName, - "version_gantt_id" => $request->version_gantt_id - ); - $result = UserToActivity::create($dataInsert); - if($result){ - $countRes++; - }else{ - $countRes--; - } - } - - if($countRes == 0) - return response()->json(['status'=>'failed' ,'message'=>'Failed to add data!','code'=> 500]); - - $allCost = $this->calculateAllCost($request->activity_id, $request->proyek_id); - $dataUpdateCost = array( - "rencana_biaya"=>$allCost, - "updated_by"=> $this->currentName - ); - $actUpdate = Activity::find($request->activity_id); - if($actUpdate){ - $actUpdate->update($dataUpdateCost); - if($actUpdate->parent_id){ - $this->updatedCostPlanning($actUpdate->parent_id); - } - } - return response()->json(['status'=>'success' ,'message'=>'Data added!','code'=>200]); - }else{ - return response()->json(['status'=>'success' ,'message'=>'Data added!','code'=>200]); - } - - } - - private function updatedCostPlanning($parent_id) { - $sumBiaya = Activity::selectRaw('sum(cast(rencana_biaya as double precision))') - ->where("parent_id", $parent_id) - ->first(); - if($parent = Activity::find($parent_id)){ - $parent->update([ - "rencana_biaya" => $sumBiaya->sum, - ]); - } - } - - public function update(Request $request, $id){ - if(empty($id) || !is_int((int)$id)) - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - - $data = UserToActivity::find($id); - if(!$data) - return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); - - if(!$data->update($request->all())); - return response()->json(['status'=>'failed','message'=>'Failed to update!','code'=> 500], 500); - - return response()->json(['status'=>'success','message'=>'Data updated!','code'=>200], 200); - } - - public function delete($id) - { - $data = UserToActivity::find($id); - if(!$data) - return response()->json(['status'=>'failed','message'=>'data user to activity gantt Project not found!','code'=>400], 400); - - if($data->delete()){ - return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); - } - - return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=> 500], 500); - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = UserToActivity::find($id); - - if(!$result) - return response()->json(['status'=>'failed','message'=>'failed get data tools resource, please try again later!','code'=>400], 400); - - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'assign_hr_to_activity'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = UserToActivity::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list user to activity gantt, please try again later!','code'=>400], 400); - } - } - - public function listFiltered(Request $request) - { - $startDate = $request->start_date; - $endDate = $request->end_date; - $userId = $request->user_id; - $proyekId = $request->proyek_id; - - if (isset($proyekId)) { - $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') - ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') - ->where('m_activity.start_date', '=', $startDate) - ->where('m_activity.end_date', '=', $endDate) - ->where('assign_hr_to_activity.user_id', '=', $userId) - ->where('assign_hr_to_activity.proyek_id', '=', $proyekId) - ->get(); - }else { - $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') - ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') - ->where('m_activity.start_date', '=', $startDate) - ->where('m_activity.end_date', '=', $endDate) - ->where('assign_hr_to_activity.user_id', '=', $userId) - ->get(); - } - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list user to activity gantt, please try again later!','code'=>400], 400); - } - } - - public function datatables(Request $request){ - $id_activity = $request->query('idact'); - $data = UserToActivity::select("assign_hr_to_activity.id as id", "u.name as user_name", "mrp.name as role_name") - ->join("m_role_proyek as mrp", "mrp.id", "=", "assign_hr_to_activity.role_proyek_id") - ->join("m_users as u", "u.id", "=", "assign_hr_to_activity.user_id") - ->where('assign_hr_to_activity.activity_id', $id_activity) - ->get(); - return Datatables::of($data) - ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; - return $actionBtn; - }) - ->rawColumns(['action'])->make(true); - } -} +validate($request, [ + 'activity_id' => 'required', + 'user_id' => 'required' + ]); + + $data = $request->all(); + $data['created_by'] = $this->currentName; + + if(!UserToActivity::create($data)) + return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500]); + + return response()->json(['status'=>'success','message'=>'Data added!', 'code'=> 200]); + } + + public function addMultiple(Request $request){ + $users_id = $request->user_id; + $users_role = $request->role_proyek_id; + + // $data = UserToActivity::where("activity_id", $request->activity_id); + // if($data){ + // $data->delete(); + // } + + if(is_array($users_id) && count($users_id) > 0){ + $countRes = 0; + foreach($users_id as $index => $item){ + $dataInsert = array( + "user_id" => $item, + "activity_id" => $request->activity_id, + "role_proyek_id" => $users_role[$index], + "proyek_id" => $request->proyek_id, + "created_by" => $this->currentName, + "version_gantt_id" => $request->version_gantt_id + ); + $result = UserToActivity::create($dataInsert); + if($result){ + $countRes++; + }else{ + $countRes--; + } + } + + if($countRes == 0) + return response()->json(['status'=>'failed' ,'message'=>'Failed to add data!','code'=> 500]); + + $allCost = $this->calculateAllCost($request->activity_id, $request->proyek_id); + $dataUpdateCost = array( + "rencana_biaya"=>$allCost, + "updated_by"=> $this->currentName + ); + $actUpdate = Activity::find($request->activity_id); + if($actUpdate){ + $actUpdate->update($dataUpdateCost); + if($actUpdate->parent_id){ + $this->updatedCostPlanning($actUpdate->parent_id); + } + } + return response()->json(['status'=>'success' ,'message'=>'Data added!','code'=>200]); + }else{ + return response()->json(['status'=>'success' ,'message'=>'Data added!','code'=>200]); + } + + } + + private function updatedCostPlanning($parent_id) { + $sumBiaya = Activity::selectRaw('sum(cast(rencana_biaya as double precision))') + ->where("parent_id", $parent_id) + ->first(); + if($parent = Activity::find($parent_id)){ + $parent->update([ + "rencana_biaya" => $sumBiaya->sum, + ]); + } + } + + public function update(Request $request, $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = UserToActivity::find($id); + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + if(!$data->update($request->all())); + return response()->json(['status'=>'failed','message'=>'Failed to update!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data updated!','code'=>200], 200); + } + + public function delete($id) + { + $data = UserToActivity::find($id); + if(!$data) + return response()->json(['status'=>'failed','message'=>'data user to activity gantt Project not found!','code'=>400], 400); + + if($data->delete()){ + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); + } + + return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=> 500], 500); + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = UserToActivity::find($id); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'failed get data tools resource, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + if (isset($payload['join_column'])) { + $join_column = $payload['join_column']; + unset($payload['join_column']); + } + + $dataBuilder = $this->setUpPayload($payload, 'assign_hr_to_activity'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + if (isset($join_column)) { + $startDate = $join_column['start_date']; + $endDate = $join_column['end_date']; + $startDate = date("Y-m-d H:i:sO", strtotime($startDate)); + $endDate = date("Y-m-d H:i:sO", strtotime($endDate)); + $builder->where(function ($query) use ($startDate, $endDate) { + $query + ->where('m_proyek.mulai_proyek', '>=', $startDate) + ->where('m_proyek.akhir_proyek', '<=', $endDate) + ->where(function ($query) use ($endDate, $startDate) { + $query + ->where('m_activity.start_date', '>=', $startDate) + ->where('m_activity.end_date', '<=', $endDate); + }); + }); + } + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = UserToActivity::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list user to activity gantt, please try again later!','code'=>400], 400); + } + } + + public function listFiltered(Request $request) + { + $startDate = $request->start_date; + $endDate = $request->end_date; + $userId = $request->user_id; + $proyekId = $request->proyek_id; + + if (isset($proyekId)) { + $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') + ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') + ->where('m_activity.start_date', '=', $startDate) + ->where('m_activity.end_date', '=', $endDate) + ->where('assign_hr_to_activity.user_id', '=', $userId) + ->where('assign_hr_to_activity.proyek_id', '=', $proyekId) + ->get(); + }else { + $data = UserToActivity::select('assign_hr_to_activity.id', 'assign_hr_to_activity.activity_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.start_date', 'm_activity.end_date') + ->join('m_activity', 'assign_hr_to_activity.activity_id', '=', 'm_activity.id') + ->where('m_activity.start_date', '=', $startDate) + ->where('m_activity.end_date', '=', $endDate) + ->where('assign_hr_to_activity.user_id', '=', $userId) + ->get(); + } + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list user to activity gantt, please try again later!','code'=>400], 400); + } + } + + public function datatables(Request $request){ + $id_activity = $request->query('idact'); + $data = UserToActivity::select("assign_hr_to_activity.id as id", "u.name as user_name", "mrp.name as role_name") + ->join("m_role_proyek as mrp", "mrp.id", "=", "assign_hr_to_activity.role_proyek_id") + ->join("m_users as u", "u.id", "=", "assign_hr_to_activity.user_id") + ->where('assign_hr_to_activity.activity_id', $id_activity) + ->get(); + return Datatables::of($data) + ->addIndexColumn() + ->addColumn('action', function($row){ + $actionBtn = ''; + return $actionBtn; + }) + ->rawColumns(['action'])->make(true); + } +} diff --git a/app/Http/Controllers/UserToProyekController.php b/app/Http/Controllers/UserToProyekController.php index fecdfec..a7a1cac 100644 --- a/app/Http/Controllers/UserToProyekController.php +++ b/app/Http/Controllers/UserToProyekController.php @@ -1,214 +1,253 @@ -validate($request, [ - 'user_id' => 'required', - 'proyek_id' => 'required' - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = UserToProyek::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'assign hr to proyek successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'assign hr to proyek failed!','code'=>400], 400); - } - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = UserToProyek::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data assign hr to proyek, please try again later!','code'=>400], 400); - } - } - - 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 = UserToProyek::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data assign hr to proyek successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = UserToProyek::find($id); - if($data){ - $userId = $data->user_id; - $proyekId = $data->proyek_id; - $delete = $data->delete(); - if($delete){ - $this->deleteRelative($proyekId, $userId); - } - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data assign hr to proyek successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data assign hr to proyek failed deleted!','code'=>400], 400); - } - } - - private function deleteRelative($proyekId, $userId) - { - $uta = UserToActivity::where("proyek_id", $proyekId)->where("user_id", $userId)->get(); - foreach ($uta as $value) { - $dataRa = ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->get(); - foreach ($dataRa as $ra) { - $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); - foreach ($images as $image) { - if(file_exists($this->pathImage.$image->image)){ - unlink($this->pathImage.$image->image); - } - } - Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); - } - ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->delete(); - } - UserToActivity::where("proyek_id", $proyekId)->where("user_id", $userId)->delete(); - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'assign_hr_to_proyek'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = UserToProyek::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list assign hr to proyek, please try again later!','code'=>400], 400); - } - } - - public function select(Request $request){ - - $search = $request->query('search'); - - $idProyek = (int)$request->query('idProyek'); - $idActivity = (int)$request->query('idact'); - - $include = []; - - if($idActivity && $idActivity > 0){ - $dataF = UserToActivity::select("user_id")->where("activity_id", $idActivity)->get(); - foreach($dataF as $val){ - $include[] = $val->user_id; - } - } - - if($search && !empty($search)){ - $data = UserToProyek::select("m_users.id as id", "m_users.name as name")->join('m_users', 'm_users.id', '=', 'assign_hr_to_proyek.user_id') - ->where("assign_hr_to_proyek.proyek_id", $idProyek)->where("m_users.name", 'like', '%'.$search.'%')->whereIn("m_users.id", $include)->get(); - }else{ - $data = UserToProyek::select("m_users.id as id", "m_users.name as name")->where("assign_hr_to_proyek.proyek_id", $idProyek)->join('m_users', 'm_users.id', '=', 'assign_hr_to_proyek.user_id')->whereIn("m_users.id", $include)->get(); - } - - if($data instanceof \Illuminate\Database\Eloquent\Collection){ - $pm = array( - "id"=>$this->currentId, - "name"=> "Project Manager" - ); - $data->push($pm); - } - - return response()->json($data); - } - - private function curlReq($url, $token){ - $ch = curl_init(); - $headers = [ - 'Authorization: '.$token - ]; - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - - $response = curl_exec($ch); - if ($response === false) - $response = curl_error($ch); - curl_close($ch); - - return json_decode($response); - } - - public function getEmployeeIntegration(Request $request) { - $search = urlencode($request->name); - if(empty($search)) - return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); - $url = str_replace("SEARCH", $search, config('api.adw').'/employees?emp_name=SEARCH'); - $token = config('api.adw_token'); - $firstResponse = $this->curlReq($url, $token); - - if($firstResponse->total == 0) - return response()->json(['status'=>'error', 'message' => 'Data not found!', 'code'=>404], 404); - - $data = $firstResponse->data; - return response()->json([$data]); - $currentPage = 1; - - if($firstResponse->last_page > 0) { - do { - $currentPage++; - $response = $this->curlReq($url.'&page='.$currentPage, $token); - foreach($response->data as $d){ - array_push($data, $d); - } - } while ($currentPage < $firstResponse->last_page); - } - - return response()->json(['status'=>'success', 'data'=> $data, 'total' => count($data), 'code'=>200], 200); - } -} +validate($request, [ + 'user_id' => 'required', + 'proyek_id' => 'required' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = UserToProyek::create($data); + + if($result){ + return response()->json(['status'=>'success','message'=>'assign hr to proyek successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'assign hr to proyek failed!','code'=>400], 400); + } + } + + public function addMultiple(Request $request){ + $user_IDs = $request->user_id; + + $data = UserToProyek::where("proyek_id", $request->proyek_id); + + if($data){ + $data->delete(); + } + + if(is_array($user_IDs) && count($user_IDs) > 0){ + $countRes = 0; + foreach($user_IDs as $item){ + + $dataInsert = array( + "user_id" => $item, + "proyek_id" => $request->proyek_id, + "created_by" => $this->currentName, + 'is_customer'=>true + ); + + $result = UserToProyek::create($dataInsert); + + if($result){ + $countRes++; + }else{ + $countRes--; + } + } + if($countRes > 0){ + return response()->json(['status'=>'success' ,'message'=>'Project customer successfull created','code'=>200]); + }else{ + return response()->json(['status'=>'success' ,'message'=>'Project customer failed created','code'=>400]); + } + }else{ + return response()->json(['status'=>'success' ,'message'=>'Project customer successfull created','code'=>200]); + } + + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = UserToProyek::find($id); + + if($result){ + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get data assign hr to proyek, please try again later!','code'=>400], 400); + } + } + + 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 = UserToProyek::find($id); + + if($data){ + $result = $data->update($request->all()); + }else{ + return response()->json(['status'=>'failed','message'=>'data assign hr to proyek not found!','code'=>400], 400); + die(); + } + + + if($result){ + return response()->json(['status'=>'success','message'=>'data assign hr to proyek successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data assign hr to proyek failed updated!','code'=>400], 400); + } + } + + public function delete($id) + { + $data = UserToProyek::find($id); + if($data){ + $userId = $data->user_id; + $proyekId = $data->proyek_id; + $delete = $data->delete(); + if($delete){ + $this->deleteRelative($proyekId, $userId); + } + }else{ + return response()->json(['status'=>'failed','message'=>'data assign hr to proyek not found!','code'=>400], 400); + die(); + } + + + if($delete){ + return response()->json(['status'=>'success','message'=>'data assign hr to proyek successfully deleted!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'data assign hr to proyek failed deleted!','code'=>400], 400); + } + } + + private function deleteRelative($proyekId, $userId) + { + $uta = UserToActivity::where("proyek_id", $proyekId)->where("user_id", $userId)->get(); + foreach ($uta as $value) { + $dataRa = ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->get(); + foreach ($dataRa as $ra) { + $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); + foreach ($images as $image) { + if(file_exists($this->pathImage.$image->image)){ + unlink($this->pathImage.$image->image); + } + } + Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); + } + ReportActivity::where("activity_id", $value->activity_id)->where("user_id", $value->user_id)->delete(); + } + UserToActivity::where("proyek_id", $proyekId)->where("user_id", $userId)->delete(); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'assign_hr_to_proyek'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = UserToProyek::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list assign hr to proyek, please try again later!','code'=>400], 400); + } + } + + public function select(Request $request){ + + $search = $request->query('search'); + + $idProyek = (int)$request->query('idProyek'); + $idActivity = (int)$request->query('idact'); + + $include = []; + + if($idActivity && $idActivity > 0){ + $dataF = UserToActivity::select("user_id")->where("activity_id", $idActivity)->get(); + foreach($dataF as $val){ + $include[] = $val->user_id; + } + } + + if($search && !empty($search)){ + $data = UserToProyek::select("m_users.id as id", "m_users.name as name")->join('m_users', 'm_users.id', '=', 'assign_hr_to_proyek.user_id') + ->where("assign_hr_to_proyek.proyek_id", $idProyek)->where("m_users.name", 'like', '%'.$search.'%')->whereIn("m_users.id", $include)->get(); + }else{ + $data = UserToProyek::select("m_users.id as id", "m_users.name as name")->where("assign_hr_to_proyek.proyek_id", $idProyek)->join('m_users', 'm_users.id', '=', 'assign_hr_to_proyek.user_id')->whereIn("m_users.id", $include)->get(); + } + + if($data instanceof \Illuminate\Database\Eloquent\Collection){ + $pm = array( + "id"=>$this->currentId, + "name"=> "Project Manager" + ); + $data->push($pm); + } + + return response()->json($data); + } + + private function curlReq($url, $token){ + $ch = curl_init(); + $headers = [ + 'Authorization: '.$token + ]; + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + + $response = curl_exec($ch); + if ($response === false) + $response = curl_error($ch); + curl_close($ch); + + return json_decode($response); + } + + public function getEmployeeIntegration(Request $request) { + $search = urlencode($request->name); + if(empty($search)) + return response()->json(['status'=>'error', 'message'=>'Empty query string!'], 400); + $url = str_replace("SEARCH", $search, config('api.adw').'/employees?emp_name=SEARCH'); + $token = config('api.adw_token'); + $firstResponse = $this->curlReq($url, $token); + + if($firstResponse->total == 0) + return response()->json(['status'=>'error', 'message' => 'Data not found!', 'code'=>404], 404); + + $data = $firstResponse->data; + return response()->json([$data]); + $currentPage = 1; + + if($firstResponse->last_page > 0) { + do { + $currentPage++; + $response = $this->curlReq($url.'&page='.$currentPage, $token); + foreach($response->data as $d){ + array_push($data, $d); + } + } while ($currentPage < $firstResponse->last_page); + } + + return response()->json(['status'=>'success', 'data'=> $data, 'total' => count($data), 'code'=>200], 200); + } +} 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/Project.php b/app/Models/Project.php index 6d3d5f4..cf2d0ad 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -1,54 +1,54 @@ -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 a207fe8..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'); @@ -292,6 +292,33 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->delete('/rate-sallary/delete/{id}', 'RateSallaryController@delete'); $router->get('/rate-sallary/list', 'RateSallaryController@list'); + $router->post('/project-checklists/add', 'ProjectChecklistsController@add'); + $router->get('/project-checklists/edit/{id}', 'ProjectChecklistsController@edit'); + $router->put('/project-checklists/update/{id}', 'ProjectChecklistsController@update'); + $router->post('/project-checklists/search', 'ProjectChecklistsController@search'); + $router->delete('/project-checklists/delete/{id}', 'ProjectChecklistsController@delete'); + $router->delete('/project-checklists/delete-by-proyek/{id}', 'ProjectChecklistsController@deleteByProyek'); + $router->get('/project-checklists/list', 'ProjectChecklistsController@list'); + $router->get('/project-checklists/{where}/{val}', 'ProjectChecklistsController@customWhere'); + + $router->post('/project-issues/add', 'ProjectIssuesController@add'); + $router->get('/project-issues/edit/{id}', 'ProjectIssuesController@edit'); + $router->put('/project-issues/update/{id}', 'ProjectIssuesController@update'); + $router->post('/project-issues/search', 'ProjectIssuesController@search'); + $router->delete('/project-issues/delete/{id}', 'ProjectIssuesController@delete'); + $router->delete('/project-issues/delete-by-proyek/{id}', 'ProjectIssuesController@deleteByProyek'); + $router->get('/project-issues/list', 'ProjectIssuesController@list'); + $router->get('/project-issues/{where}/{val}', 'ProjectIssuesController@customWhere'); + + $router->post('/project-risks/add', 'ProjectRisksController@add'); + $router->get('/project-risks/edit/{id}', 'ProjectRisksController@edit'); + $router->put('/project-issues/update/{id}', 'ProjectRisksController@update'); + $router->post('/project-risks/search', 'ProjectRisksController@search'); + $router->delete('/project-risks/delete/{id}', 'ProjectRisksController@delete'); + $router->delete('/project-risks/delete-by-proyek/{id}', 'ProjectRisksController@deleteByProyek'); + $router->get('/project-risks/list', 'ProjectRisksController@list'); + $router->get('/project-risks/{where}/{val}', 'ProjectRisksController@customWhere'); + $router->post('/project-participants/add', 'ProjectParticipantsController@add'); $router->get('/project-participants/edit/{id}', 'ProjectParticipantsController@edit'); $router->put('/project-participants/update/{id}', 'ProjectParticipantsController@update'); @@ -381,6 +408,7 @@ $router->group(['prefix'=>'api', 'middleware' => 'cors'], function () use ($rout $router->get('/report-k3-detail/list', 'ReportK3DetailController@list'); $router->post('/user-to-proyek/add', 'UserToProyekController@add'); + $router->post('/user-to-proyek/add-multiple', 'UserToProyekController@addMultiple'); $router->get('/user-to-proyek/edit/{id}', 'UserToProyekController@edit'); $router->put('/user-to-proyek/update/{id}', 'UserToProyekController@update'); $router->post('/user-to-proyek/search', 'UserToProyekController@search');