Custom Backend OSPRO Surveyor Indonesia
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

547 lines
22 KiB

<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Divisi;
use App\Models\Activity;
use App\Models\AssignMaterial;
use App\Models\Company;
use App\Models\ReportK3Detail;
use App\Models\UserToActivity;
use App\Models\ProductTransaction;
use App\Models\Project;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Laravel\Lumen\Routing\Controller as BaseController;
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
use Exception;
class Controller extends BaseController
{
protected $pathImage = "assets/image/";
protected $pathDocument = "assets/file/project/";
protected $pathTmpImport = "assets/file/tmpimport/";
protected $pathActivityDocument = "assets/file/activity/";
protected $listJoinAll = [
'first', 'second', 'third', 'fourth', 'fifth',
'sixth', 'seventh', 'eighth', 'ninth', 'tenth'
];
protected $currentDate;
protected $currentName;
protected $currentId;
protected $companyId;
public function __construct()
{
$this->currentDate = date("Y-m-d H:i:s");
$this->currentName = auth()->user() ? auth()->user()->name : "system";
$this->currentId = auth()->user() ? auth()->user()->id : 0;
$this->pathImage = config('assets.image');
$this->pathDocument = config('assets.project');
$this->pathActivityDocument = config('assets.activity');
}
protected function setCustomeDirectoryUpload()
{
$current_date = date('Y-m-d');
[$year, $month] = explode('-', $current_date);
$yearMonth = $year.'-'.$month;
$pathImage = 'assets/image/';
$pathDocument = 'assets/file/project/';
$pathTmpImport = 'assets/file/tmpimport/';
$pathActivityDocument = 'assets/file/activity/';
return [
'pathImage' => $pathImage,
'pathDocument' => $pathDocument,
'pathTmpImport' => $pathTmpImport,
'pathActivityDocument' => $pathActivityDocument
];
}
public function storage($company_name)
{
$directory = 'assets/' . urldecode($company_name);
if (!is_dir($directory)) {
return "Directory not found";
}
$size = 0;
try {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
$size += $file->getSize();
}
} catch (Exception $e) {
return "Error while calculating size: " . $e->getMessage();
}
return round($size / 1048576, 2);
}
public function storageAllCompany()
{
$companies = Company::get();
$formData = [];
foreach($companies as $data) {
$size = 0;
$directory = 'assets/' . urldecode($data['company_name']);
if (is_dir($directory)) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
$size += $file->getSize();
}
}
$formData[] = [
'company_name' => $data['company_name'],
'size' => round($size / 1048576, 2),
'exp_ospro' => ProductTransaction::query()->where('company_id', $data['id'])->value('exp_ospro'),
'project_total' => Project::query()->where('company_id',$data['id'])->count()
];
}
return $formData;
}
public function setExpiredTimeOspro($company_id)
{
$currentDate = Carbon::now();
$countCreate = false;
$transaction = ProductTransaction::query()
->where('company_id', $company_id)->first();
if(!empty($transaction)) {
$dateExpired = $transaction['exp_ospro'];
if ($currentDate->gt(Carbon::parse($dateExpired))) {
$countCreate = false;
} else {
$countCreate = true;
}
return $countCreate;
} else {
return $countCreate = true;
}
}
protected function setLimitsStorage($company, $dokumen, $initPath, $destinatePath)
{
$countCreate = false;
DB::transaction(function() use($company, $dokumen, $initPath, $destinatePath, &$countCreate) {
$totalSize = 0;
$sizeFile = $dokumen->getSize();
// Path
$folderPath = $destinatePath['pathDocument'];
$folderPathImage = $destinatePath['pathImage'];
$folderPathTmpImport = $destinatePath['pathTmpImport'];
$folderPathActivityDocument = $destinatePath['pathActivityDocument'];
// Create Directory
if (!file_exists($initPath)) {
mkdir($initPath, 0777, true);
}
// Scanning & Existing Folder
if (file_exists($folderPathImage)) {
$files = scandir($folderPathImage);
foreach ($files as $file) {
if (is_file($folderPathImage . '/' . $file)) {
$totalSize += filesize($folderPathImage . '/' . $file);
}
}
}
if (file_exists($folderPath)) {
$filesImage = scandir($folderPath);
foreach ($filesImage as $file) {
if (is_file($folderPath . '/' . $file)) {
$totalSize += filesize($folderPath . '/' . $file);
}
}
}
if (file_exists($folderPathTmpImport)) {
$filesTmpImport = scandir($folderPathTmpImport);
foreach ($filesTmpImport as $file) {
if (is_file($folderPathTmpImport . '/' . $file)) {
$totalSize += filesize($folderPathTmpImport . '/' . $file);
}
}
}
if (file_exists($folderPathActivityDocument)) {
$filesActivityDocument = scandir($folderPathActivityDocument);
foreach ($filesActivityDocument as $file) {
if (is_file($folderPathActivityDocument . '/' . $file)) {
$totalSize += filesize($folderPathActivityDocument . '/' . $file);
}
}
}
// Logic
$totalSize += $sizeFile;
$transaction = ProductTransaction::query()
->where('company_id', $company['id']);
$cloneQueryTransaction = clone $transaction;
if ($transaction->where([['type_paket', 'Basic'], ['amount', '!=', null]])->exists()) {
$maximumSize = 500 * 1024 * 1024;
$countCreate = true;
} elseif ($cloneQueryTransaction->where([['type_paket', 'Free'], ['amount', 0]])->exists()) {
$maximumSize = 50 * 1024 * 1024;
$countCreate = true;
} else {
$countCreate = true;
}
if ($countCreate && isset($maximumSize)) { // kondisi $maximumSize sementara karena blm ada paket enterprise
if (floatval($totalSize) > floatval($maximumSize)) {
$countCreate = false;
}
}
});
return $countCreate;
}
protected function setUpPayload($condition, $tableSelf)
{
$alias = "selfTable";
$builder = DB::table($tableSelf . " AS " . $alias);
// $builder = $builder->select($alias.".*");
if ($condition) {
if (isset($condition['select'])) {
foreach ($condition['select'] as $select) {
$builder = $builder->addSelect($alias . "." . $select);
}
} else {
$builder = $builder->addSelect($alias . ".*");
}
if (isset($condition['joins'])) {
$selectColumn = [];
$no = 0;
foreach ($condition['joins'] as $join) {
$tableJoin = isset($join['name1']) ? $join['name1'] : $alias;
$tableName = $join['name'];
$columnJoin = $join['column_join']; // foreign key table sini
$columnSelf = isset($join['column_self']) ? $join['column_self'] : "id"; // primary key table lawan
if (isset($join['column_results'])) {
$columnResult = $join['column_results'];
foreach ($columnResult as $sColumn) {
$builder = $builder->addSelect($tableName . "." . $sColumn . " as join_" . $this->listJoinAll[$no] . "_" . $sColumn);
}
}
$builder = $builder->leftJoin($tableName, $tableJoin . "." . $columnJoin, '=', $tableName . '.' . $columnSelf);
$no++;
}
}
if (isset($condition['columns'])) {
$listWhere = $condition['columns'];
$builder = $builder->where(function ($query) use ($listWhere, $alias) {
foreach ($listWhere as $where) {
$value = $where['value'];
if ($value && $value != "" && $value != " ") {
$column = $where['name'];
$operator = strtolower($where['logic_operator']); // like, =, <>, range
$value2 = isset($where['value1']) ? $where['value1'] : "";
$tableColumn = isset($where['table_name']) ? $where['table_name'] : $alias;
$query = $this->whereCondition($query, $operator, $tableColumn, $column, $value, $value2);
}
}
});
}
if (isset($condition['group_column'])) {
$builder = $this->groupWhere($builder, $condition['group_column'], $alias);
}
$data['count'] = clone $builder;
if (isset($condition['paging'])) {
$builder = $builder->offset($condition['paging']['start'])->limit($condition['paging']['length']);
}
if (isset($condition['orders'])) {
$orders = $condition['orders'];
$sortBy = $orders['ascending'] ? "ASC" : "DESC";
$columnOrder = $orders['columns'];
foreach ($columnOrder as $column) {
$builder = $builder->orderBy($alias . "." . $column, $sortBy);
}
}
}
$data['builder'] = $builder;
return $data;
}
private function groupWhere($oldBuilder, $groupWhere, $alias)
{
$builder = $oldBuilder;
$listGroupWhere = $groupWhere;
$operator = $listGroupWhere['operator'];
$operatorGroup = $listGroupWhere['group_operator'];
$listWhere = $listGroupWhere['where'];
if (strtolower($operator) == "and") {
$builder = $builder->where(function ($query) use ($operatorGroup, $listWhere, $alias) {
$no = 1;
foreach ($listWhere as $where) {
$value = $where['value'];
$column = $where['name'];
$operator = strtolower($where['logic_operator']);
$value2 = isset($where['value1']) ? $where['value1'] : "";
$tableColumn = isset($where['table_name']) ? $where['table_name'] : $alias;
if ($value && $value != "" && $value != " ") {
if ($operatorGroup == "and") {
$query = $this->whereCondition($query, $operator, $tableColumn, $column, $value, $value2);
} else {
if ($no == 1) {
$query = $this->whereCondition($query, $operator, $tableColumn, $column, $value, $value2);
} else {
$query = $this->orWhereCondition($query, $operator, $tableColumn, $column, $value, $value2);
}
}
}
$no = $no + 1;
}
});
} else if (strtolower($operator) == "or") {
$builder = $builder->orWhere(function ($query) use ($operatorGroup, $listWhere, $alias) {
$no = 1;
foreach ($listWhere as $where) {
$value = $where['value'];
$column = $where['name'];
$operator = strtolower($where['logic_operator']);
$value2 = isset($where['value1']) ? $where['value1'] : "";
$tableColumn = isset($where['table_name']) ? $where['table_name'] : $alias;
if ($value && $value != "" && $value != " ") {
if ($operatorGroup == "and") {
$query = $this->whereCondition($query, $operator, $tableColumn, $column, $value, $value2);
} else {
if ($no == 1) {
$query = $this->whereCondition($query, $operator, $tableColumn, $column, $value, $value2);
} else {
$query = $this->orWhereCondition($query, $operator, $tableColumn, $column, $value, $value2);
}
}
}
$no++;
}
});
}
return $builder;
}
private function whereCondition($oldQuery, $operator, $tableColumn, $column, $value, $value2)
{
$query = $oldQuery;
if ($operator == "range") {
$query = $query->whereBetween($tableColumn . "." . $column, [$value, $value2]);
} else if ($operator == "like") {
$query = $query->where($tableColumn . "." . $column, 'like', '%' . $value . '%');
} else if ($operator == "ilike") {
$query = $query->where($tableColumn . "." . $column, '~*', $value);
} else if ($operator == "=") {
$query = $query->where($tableColumn . "." . $column, $value);
} else if ($operator == "in") {
$query = $query->whereIn($tableColumn . "." . $column, $value);
} else if ($operator == "notin") {
$query = $query->whereNotIn($tableColumn . "." . $column, $value);
} else if ($operator == "isnull") {
$query = $query->WhereNull($tableColumn . "." . $column);
} else if ($operator == "notnull") {
$query = $query->WhereNotNull($tableColumn . "." . $column);
} else {
$query = $query->where($tableColumn . "." . $column, $operator, $value);
}
return $query;
}
private function whereConditionSingleTable($oldQuery, $operator, $column, $value, $value2)
{
$query = $oldQuery;
if ($operator == "range") {
$query = $query->whereBetween($column, [$value, $value2]);
} else if ($operator == "like") {
$query = $query->where($column, 'like', '%' . $value . '%');
} else if ($operator == "ilike") {
$query = $query->where($column, '~*', $value);
} else if ($operator == "=") {
$query = $query->where($column, $value);
} else if ($operator == "in") {
$query = $query->whereIn($column, $value);
} else if ($operator == "notin") {
$query = $query->whereNotIn($column, $value);
} else {
$query = $query->where($column, $operator, $value);
}
return $query;
}
private function orWhereCondition($oldQuery, $operator, $tableColumn, $column, $value, $value2)
{
$query = $oldQuery;
if ($operator == "range") {
$query = $query->orWhereBetween($tableColumn . "." . $column, [$value, $value2]);
} else if ($operator == "like") {
$query = $query->orWhere($tableColumn . "." . $column, 'like', '%' . $value . '%');
} else if ($operator == "ilike") {
$query = $query->where($tableColumn . "." . $column, '~*', $value);
} else if ($operator == "=") {
$query = $query->orWhere($tableColumn . "." . $column, $value);
} else if ($operator == "in") {
$query = $query->orWhereIn($tableColumn . "." . $column, $value);
} else if ($operator == "notin") {
$query = $query->orWhereNotIn($tableColumn . "." . $column, $value);
} else {
$query = $query->orWhere($tableColumn . "." . $column, $operator, $value);
}
return $query;
}
protected function calculateAllCost($activity_id, $proyek_id)
{
$humanCostPlanning = $this->calculateAllHumanCost($activity_id, $proyek_id);
$materialCostPlanning = $this->calculateMaterialCost($activity_id, $proyek_id);
$toolsCostPlanning = 0;
$allCost = $humanCostPlanning + $materialCostPlanning + $toolsCostPlanning;
return $allCost;
}
private function calculateAllHumanCost($activity_id, $proyek_id)
{
$dataHuman = UserToActivity::select("ahp.standart_rate as standart_rate", "ahp.max_used as max_used", "ahp.cost_per_used as cost_per_used", "ahp.uom_standart_rate as uom_standart_rate")
->leftJoin("assign_hr_to_proyek as ahp", "assign_hr_to_activity.user_id", "=", "ahp.user_id")
->where("assign_hr_to_activity.activity_id", $activity_id)->where("assign_hr_to_activity.proyek_id", $proyek_id)
->where("ahp.proyek_id", $proyek_id)
->get();
$totalCost = 0;
foreach ($dataHuman as $human) {
$totalCost += $this->calculateHumanCost($human, $activity_id);
}
return $totalCost;
}
private function calculateHumanCost($human, $activity_id)
{
$activity = Activity::find($activity_id);
$duration = $activity->duration;
$standarRate = $human->standart_rate;
$maxUsed = $human->max_used / 100;
if ($human->uom_standart_rate == "Hour") {
$totalCost = ($standarRate * 8 * $duration) * $maxUsed;
return $totalCost;
}
$totalCost = ($standarRate * $duration) * $maxUsed;
return $totalCost;
}
private function calculateMaterialCost($activity_id, $proyek_id)
{
$totalCost = AssignMaterial::selectRaw("COALESCE(qty_planning,0)*COALESCE(budget,0) as totalCost")
->where("proyek_id", $proyek_id)
->where("activity_id", $activity_id)
->sum(AssignMaterial::raw("COALESCE(qty_planning, 0) * COALESCE(budget, 0)"));
return $totalCost;
}
protected function paramsMethodGet($query, $countData, $request)
{
$start = $request->start;
$length = $request->length == '-1' ? $countData : $request->length;
$orderBy = $request->orderby;
$asc = $request->asc == 'false' ? 'desc' : 'asc';
$where = $request->column;
$logicOp = $request->logic;
$valColumn = str_replace("\\", "", "$request->value");
if ($logicOp == 'like' || $logicOp == 'ilike') {
$valColumnFilter = '%' . $valColumn . '%';
} else {
$valColumnFilter = $valColumn;
}
$data = $query->where($where, $logicOp, $valColumnFilter)
->orderBy($orderBy, $asc)
->offset($start)->limit($length)->get();
return $data;
}
protected function getLoc($lat, $lng)
{
// $response = Http::get(config('api.nominatim') . "/reverse?lat=".$lat."&lon=".$lng."&format=json");
// return $response->json;
$url = config('api.nominatim') . "/reverse?lat=" . $lat . "&lon=" . $lng . "&format=json";
// $token = config('api.adw_token');
$response = $this->curlRequest($url);
return $response;
}
private function curlRequest($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if ($response === false)
$response = curl_error($ch);
curl_close($ch);
return json_decode($response);
}
protected function addDetailK3($dataDetail, $report_id)
{
foreach ($dataDetail as $value) {
$dataNew = array(
"report_k3_id" => $report_id,
"checklist_k3_id" => $value['checklist_id'],
"name_checklist_k3" => $value['checklist_name'],
"created_by" => $this->currentName
);
ReportK3Detail::create($dataNew);
}
}
protected function getDataHierarchy($divisi, $paramUserId)
{
$parentDivisi = Divisi::where('id', $divisi)->get();
$divisions = [];
$tempUser = [];
$userId = [$paramUserId];
// if ($parentDivisi->parent == null){
// }else{
foreach ($parentDivisi as $key) {
$data = $this->getAllChildrenDivisi($key->id);
$divisions[] = $data;
}
if (count($divisions) > 0) {
for ($i = 0; $i < count($divisions[0]); $i++) {
if (User::select('id', 'name', 'divisi_id')->where('divisi_id', $divisions[0][$i]->id)->exists()) {
$tempUser[] = User::select('id', 'name', 'divisi_id')->where('divisi_id', $divisions[0][$i]->id)->get();
}
}
for ($x = 0; $x < count($tempUser); $x++) {
for ($y = 0; $y < count($tempUser[$x]); $y++) {
$userId[] = $tempUser[$x][$y]->id;
}
}
}
return $userId;
// }
// return $userId;
}
private function getAllChildrenDivisi($divisi)
{
$finalData = [];
$divisi = Divisi::where('parent', $divisi)->get();
if (count($divisi) > 0) {
foreach ($divisi as $key) {
$childDivisi = $this->getAllChildrenDivisi($key->id);
$finalData[] = $key;
$finalData = array_merge($finalData, $childDivisi);
}
}
return $finalData;
}
}