2478 lines
69 KiB
PHP
2478 lines
69 KiB
PHP
<?php
|
||
|
||
namespace App\Http\Controllers;
|
||
|
||
|
||
|
||
use Illuminate\Support\Facades\Auth;
|
||
use Illuminate\Database\Schema\Blueprint;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Http\Request;
|
||
use Illuminate\Support\Facades\Input;
|
||
use App\Contents;
|
||
use App\Types;
|
||
use App\Fields;
|
||
use App\User;
|
||
use Carbon\Carbon;
|
||
use App\DevExtreme\Utils;
|
||
use App\DevExtreme\FilterHelper;
|
||
use App\DevExtreme\DbSet;
|
||
|
||
use Illuminate\Auth\Events\Registered;
|
||
use Maatwebsite\Excel\Facades\Excel;
|
||
use App\Imports\ImportExcel;
|
||
use App\Exports\ExportExcel;
|
||
use Illuminate\Support\Facades\Artisan;
|
||
use Cache;
|
||
use Illuminate\Support\Facades\Storage;
|
||
use App\Models\ColumnComment;
|
||
use Illuminate\Support\Facades\Session;
|
||
use Illuminate\Support\Facades\Log;
|
||
use App\Jobs\ExecuteSaveTriggerJob;
|
||
|
||
class AdminController extends Controller
|
||
{
|
||
private $currentTable;
|
||
|
||
// Global settings variable for weld log edit time limit except levels
|
||
private $weldLogEditTimeLimitExceptLevels;
|
||
|
||
public function __construct()
|
||
{
|
||
$this->middleware('auth');
|
||
if(!app()->runningUnitTests()) {
|
||
$contents = Contents::where("kid","main")
|
||
->orderBy("s","ASC")
|
||
->get(); // tüm içeriklerdeki ana içerikler gelecek
|
||
$types = Types::orderBy("id","DESC")->get(); // tüm tipler
|
||
|
||
// Load weld log edit time limit except levels from settings
|
||
$this->weldLogEditTimeLimitExceptLevels = j(setting('weld_log_edit_time_limit_except_levels'));
|
||
if(empty($this->weldLogEditTimeLimitExceptLevels)) {
|
||
$this->weldLogEditTimeLimitExceptLevels = [
|
||
'Admin',
|
||
'Manager (Center Office)',
|
||
'Manager (PTO)',
|
||
'Manager (Lead)',
|
||
'Quality Staff',
|
||
];
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Önbelleğe alınmış dashboard sayfasını görüntüler
|
||
* Eğer önbellek dosyası yoksa gerçek zamanlı oluşturur
|
||
*/
|
||
public function cachedDashboard()
|
||
{
|
||
if (Storage::exists('cache/dashboard.blade.php')) {
|
||
$dashboardContent = Storage::get('cache/dashboard.blade.php');
|
||
$lastUpdated = Storage::exists('cache/dashboard_last_updated.txt')
|
||
? Storage::get('cache/dashboard_last_updated.txt')
|
||
: date('Y-m-d H:i:s');
|
||
|
||
return view('admin.dashboard.index', [
|
||
'dashboardContent' => $dashboardContent,
|
||
'lastUpdated' => $lastUpdated
|
||
]);
|
||
} else {
|
||
// Önbellek bulunamadı, cron dosyasını çalıştır
|
||
$dashboardContent = view('admin.dashboard.module.dashboard')->render();
|
||
return view('admin.dashboard.index', [
|
||
'dashboardContent' => $dashboardContent,
|
||
'lastUpdated' => date('Y-m-d H:i:s') . ' (cache not found)'
|
||
]);
|
||
}
|
||
}
|
||
|
||
public function importStatus() {
|
||
$id = session('import');
|
||
return response([
|
||
'started' => filled(cache("start_date_$id")),
|
||
'finished' => filled(cache("end_date_$id")),
|
||
'current_row' => (int) cache("current_row_$id"),
|
||
'total_rows' => (int) cache("total_rows_$id"),
|
||
]);
|
||
|
||
}
|
||
|
||
public function logout() {
|
||
Auth::logout();
|
||
Session::forget('cached_user');
|
||
return redirect('login');
|
||
}
|
||
|
||
public function action2(string $action="",string $type ="") {
|
||
if($type=="types") {
|
||
$types = new Types;
|
||
$types->title = "";
|
||
$types->slug = "";
|
||
$types->save();
|
||
return back();
|
||
|
||
|
||
}
|
||
}
|
||
public function action(string $type="",string $id="",string $action ="") {
|
||
$this->middleware('auth');
|
||
if($type=="contents") {
|
||
switch($action) {
|
||
case "add" :
|
||
$c = Contents::where("slug",$id)->first();
|
||
$content = new Contents;
|
||
$content->title = "";
|
||
$content->slug = rand(1111111,99999999);
|
||
$content->tkid = json_encode(Contents::getTree($id));
|
||
$content->breadcrumb = Contents::getBreadcrumbs($id,"{title} / ");
|
||
if(isset($c->type)) {
|
||
$content->type = $c->type;
|
||
}
|
||
|
||
$content->kid = $id;
|
||
$content->save();
|
||
return redirect("admin/$type/$id");
|
||
break;
|
||
case "delete":
|
||
$content = Contents::where('slug', $id)->orWhere("id",$id)->delete();
|
||
return back();
|
||
break;
|
||
|
||
}
|
||
}
|
||
if($type=="types") {
|
||
switch($action) {
|
||
|
||
case "delete":
|
||
$content = Types::where('id', $id)->delete();
|
||
return back();
|
||
break;
|
||
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
public function new(string $type="") {
|
||
$this->middleware('auth');
|
||
$contents = Contents::where("kid","main")
|
||
->orderBy("s","ASC")
|
||
->get(); // tüm içeriklerdeki ana içerikler gelecek
|
||
$types = Types::orderBy("id", "DESC")->get(); // tüm tipler
|
||
$var = [
|
||
'type' => $type,
|
||
'contents' => $contents,
|
||
"types" => $types
|
||
];
|
||
try {
|
||
return view("admin/new/$type",$var);
|
||
} catch (\Exception $e) {
|
||
return abort(404);
|
||
}
|
||
}
|
||
|
||
public function exportExcel(Request $request, string $tableName, string $fileName="") {
|
||
|
||
|
||
if($fileName=="") {
|
||
$fileName = $tableName;
|
||
}
|
||
if($request->filter) {
|
||
dd($request->filter);
|
||
}
|
||
$columnNames = [];
|
||
if($request->columns) {
|
||
$columnNames = $request->columns;
|
||
}
|
||
|
||
if(!getesit("module","")) {
|
||
$fileName = get("module");
|
||
}
|
||
|
||
$excel = new ExportExcel($tableName, $columnNames);
|
||
$response = Excel::download($excel, $fileName . '.xlsx');
|
||
ob_end_clean();
|
||
return $response;
|
||
}
|
||
|
||
public function importExcel(Request $request, string $tableName) {
|
||
|
||
$id = now()->unix();
|
||
session([ 'import' => $id ]);
|
||
|
||
if(!is_null($request->file('excel-file'))) {
|
||
Excel::queueImport(new ImportExcel($tableName, $id),
|
||
$request->file('excel-file')->store('files'));
|
||
|
||
}
|
||
|
||
|
||
|
||
}
|
||
|
||
public function truncateTable(Request $request, string $tableName) {
|
||
$u = u();
|
||
if($u->level == "Admin") {
|
||
$query = db($tableName);
|
||
if($tableName=="users") {
|
||
$query = $query->where(function($q) {
|
||
$q->orWhereNull("permissions");
|
||
$q->orWhereNull("email");
|
||
$q->orWhereNull("recover");
|
||
|
||
});
|
||
|
||
$jobDesc = db("job_descriptions")->get()->pluck("title")->toArray();
|
||
$jobDesc[] = null;
|
||
$query = $query->whereIn("level", $jobDesc)->delete();
|
||
} else {
|
||
$query->truncate();
|
||
}
|
||
Artisan::call('cache:clear');
|
||
}
|
||
|
||
|
||
|
||
return redirect()->back();
|
||
}
|
||
|
||
public function delete(string $tableName, int $id) {
|
||
$query = db($tableName);
|
||
if($tableName == "users") {
|
||
$query = $query->where(function($q) {
|
||
$q->orWhereNull("permissions");
|
||
$q->orWhereNull("email");
|
||
$q->orWhereNull("recover");
|
||
|
||
});
|
||
|
||
$jobDesc = db("job_descriptions")->get()->pluck("title")->toArray();
|
||
$jobDesc[] = null;
|
||
$query = $query->whereIn("level", $jobDesc);
|
||
} elseif($tableName == "weld_logs") {
|
||
|
||
|
||
|
||
}
|
||
echo $query->where("id", $id)->delete();
|
||
}
|
||
|
||
public function exceptionFields($filterColumn, $filterValue) {
|
||
if($filterColumn == "naks_id") {
|
||
$pattern = '/\[(.*?)\]/';
|
||
if (preg_match($pattern, $filterValue, $matches)) {
|
||
$result = $matches[1];
|
||
return $result;
|
||
} else {
|
||
return $filterValue;
|
||
}
|
||
} elseif($filterColumn == "short_number-certificate_no") {
|
||
dd($filterColumn);
|
||
} else {
|
||
return $filterValue;
|
||
}
|
||
}
|
||
|
||
public function responseJSON($data) {
|
||
return response()->json(
|
||
($data),
|
||
200,
|
||
[
|
||
'Content-Type' => 'application/json;charset=UTF-8',
|
||
'Charset' => 'utf-8'
|
||
],
|
||
JSON_UNESCAPED_UNICODE
|
||
);
|
||
}
|
||
|
||
public function autocompleteType(string $type) {
|
||
|
||
$rowData = json_decode(get("row"));
|
||
|
||
if(is_null($rowData))
|
||
{
|
||
$rowData = (object) request()->all();
|
||
}
|
||
|
||
if(getisset('$filter')) {
|
||
$text = get('$filter');
|
||
$pattern = "/'([^']+)'/";
|
||
if (preg_match($pattern, $text, $matches)) {
|
||
$substring = $matches[1];
|
||
// echo $substring;
|
||
$_GET['value'] = $substring;
|
||
}
|
||
}
|
||
if(isset($rowData->naks_technology)) {
|
||
$naksTechDatas = explode(" + ", $rowData->naks_technology);
|
||
$certificateNo = [];
|
||
foreach($naksTechDatas AS $naksTechData) {
|
||
$certificateNo[] = explode("-", $naksTechData)[2];
|
||
}
|
||
}
|
||
$type = str_replace("*", "/", $type);
|
||
include(base_path("app/Http/Controllers/AutoCompleteType/$type.php"));
|
||
return $this->responseJSON($response);
|
||
|
||
|
||
|
||
}
|
||
|
||
public function autocomplete(string $tableName, string $columnName) {
|
||
$query = db($tableName);
|
||
|
||
if(getisset('$filter')) {
|
||
$text = get('$filter');
|
||
$pattern = "/'([^']+)'/";
|
||
if (preg_match($pattern, $text, $matches)) {
|
||
$substring = $matches[1];
|
||
// echo $substring;
|
||
$_GET['value'] = $substring;
|
||
}
|
||
}
|
||
|
||
if(getisset("filter")) {
|
||
$filter = json_decode(get("filter"), true);
|
||
foreach($filter AS $filterColumn => $filterValue) {
|
||
$filterValue = $this->exceptionFields($filterColumn, $filterValue);
|
||
$query = $query->where($filterColumn, $filterValue);
|
||
}
|
||
}
|
||
|
||
if(getisset("filter_multi")) {
|
||
$filter = json_decode(get("filter_multi"), true);
|
||
|
||
foreach($filter AS $filterColumn => $filterValues) {
|
||
$filterValues = explode(",", $filterValues);
|
||
$query = $query->whereIn($filterColumn, $filterValue);
|
||
}
|
||
}
|
||
|
||
|
||
if(!getesit("value", "")) {
|
||
$value = get("value");
|
||
$query = $query->where($columnName,"like","%$value%");
|
||
|
||
}
|
||
|
||
$take = 20;
|
||
if(!getesit("take", "")) {
|
||
$take = get("take");
|
||
}
|
||
$query = $query->take($take);
|
||
|
||
if(!getesit("values", "")) {
|
||
$whereInColumnName = $columnName;
|
||
|
||
if(!getesit("column", "")) {
|
||
$whereInColumnName = get("column");
|
||
}
|
||
|
||
$values = explode(",", get("values"));
|
||
$query = $query->whereIn($whereInColumnName, $values);
|
||
}
|
||
|
||
if(!getesit("pattern", "")) {
|
||
$columns = get_variables_from_pattern(get("pattern"));
|
||
//dd($columns);
|
||
$query = $query->groupBy($columns)->get($columns)->toArray();
|
||
$result = [];
|
||
foreach($query AS $q) {
|
||
$pattern = get("pattern");
|
||
foreach($columns AS $column) {
|
||
$pattern = str_replace("{".$column."}", $q->$column, $pattern);
|
||
}
|
||
/// dd($pattern);
|
||
$result[] = $pattern;
|
||
}
|
||
$query = $result;
|
||
} else {
|
||
if(!getisset("all")) {
|
||
$query = $query->select($columnName);
|
||
$query = $query->groupBy($columnName);
|
||
}
|
||
|
||
|
||
|
||
if(getisset("with-column")) {
|
||
$query = $query->get();
|
||
} else {
|
||
$query = $query->pluck($columnName);
|
||
}
|
||
|
||
}
|
||
|
||
|
||
return $this->responseJSON($query);
|
||
|
||
}
|
||
|
||
public function fuzzyAutocomplete(string $tableName, ?string $columnName = null) {
|
||
if (empty($columnName)) {
|
||
return $this->responseJSON([]);
|
||
}
|
||
|
||
$searchTerm = request('search', '');
|
||
$limit = (int) request('limit', 20);
|
||
|
||
$existingValues = [];
|
||
try {
|
||
$existingValues = db($tableName)
|
||
->whereNotNull($columnName)
|
||
->where($columnName, '!=', '')
|
||
->distinct()
|
||
->pluck($columnName)
|
||
->filter()
|
||
->values()
|
||
->toArray();
|
||
} catch (\Exception $e) {
|
||
dd($e);
|
||
}
|
||
|
||
// Build values array
|
||
$allValues = [];
|
||
foreach ($existingValues as $value) {
|
||
$allValues[] = [
|
||
'value' => $value,
|
||
'display' => $value
|
||
];
|
||
}
|
||
|
||
if (!empty($searchTerm)) {
|
||
$searchTerm = strtolower($searchTerm);
|
||
$results = [];
|
||
|
||
foreach ($allValues as $item) {
|
||
$value = strtolower($item['value']);
|
||
|
||
$score = 0;
|
||
|
||
// Exact match (highest priority)
|
||
if ($value === $searchTerm) {
|
||
$score = 100;
|
||
}
|
||
elseif (strpos($value, $searchTerm) === 0) {
|
||
$score = 80;
|
||
}
|
||
elseif (strpos($value, $searchTerm) !== false) {
|
||
$score = 60;
|
||
}
|
||
else {
|
||
$distance = levenshtein($searchTerm, substr($value, 0, strlen($searchTerm) + 2));
|
||
if ($distance <= 2) {
|
||
$score = 40 - ($distance * 10);
|
||
}
|
||
}
|
||
|
||
if ($score > 0) {
|
||
$item['score'] = $score;
|
||
$results[] = $item;
|
||
}
|
||
}
|
||
|
||
usort($results, function($a, $b) {
|
||
return $b['score'] - $a['score'];
|
||
});
|
||
|
||
$seen = [];
|
||
$uniqueResults = [];
|
||
foreach ($results as $item) {
|
||
if (!in_array($item['value'], $seen)) {
|
||
$seen[] = $item['value'];
|
||
unset($item['score']); // Remove score from output
|
||
$uniqueResults[] = $item;
|
||
}
|
||
if (count($uniqueResults) >= $limit) break;
|
||
}
|
||
|
||
return $this->responseJSON($uniqueResults);
|
||
}
|
||
|
||
$uniqueResults = array_slice($allValues, 0, $limit);
|
||
|
||
return $this->responseJSON($uniqueResults);
|
||
}
|
||
|
||
public function linkCreator(Request $request, string $tableName, string $id) {
|
||
|
||
$prefix = $tableName.$id . md5(get("data"));
|
||
/*
|
||
if(Cache::has($prefix)) {
|
||
return Cache::get($prefix);
|
||
} else {
|
||
*/
|
||
|
||
$thisData = db($tableName)->where("id", $id)->first();
|
||
$data = j($_GET['data']);
|
||
|
||
if(!is_null($thisData)) {
|
||
$data['pattern'] = str_replace(".pdf", ".[pP][dD][fF]", $data['pattern']);
|
||
$pattern = $data['pattern'];
|
||
$pattern2 = $data['pattern'];
|
||
foreach($thisData AS $listColumn => $listValue) {
|
||
$listValue = str_replace("/", "*", $listValue);
|
||
$listValue = str_replace(" ", "*", $listValue);
|
||
// $listValue = str_replace("-", "*", $listValue);
|
||
|
||
if($listValue != "") {
|
||
$pattern = str_replace("{". $listColumn ."}", $listValue, $pattern);
|
||
}
|
||
|
||
|
||
}
|
||
foreach($thisData AS $listColumn => $listValue) {
|
||
$listValue = strtolower($listValue);
|
||
$listValue = str_replace("/", "*", $listValue);
|
||
$listValue = str_replace(" ", "*", $listValue);
|
||
// $listValue = str_replace("-", "*", $listValue);
|
||
|
||
if($listValue != "") {
|
||
$pattern2 = str_replace("{". $listColumn ."}", $listValue, $pattern2);
|
||
}
|
||
|
||
}
|
||
|
||
$fullPath = "storage/documents/" . $data['path'] . $pattern;
|
||
$fullPath2 = "storage/documents/" . $data['path'] . $pattern2;
|
||
$search = glob($fullPath, GLOB_BRACE);
|
||
|
||
if(count($search) == 0) {
|
||
$search = glob($fullPath2);
|
||
|
||
}
|
||
|
||
if(isset($search[0])) {
|
||
$url = url($search[0]);
|
||
Cache::put($prefix, $url);
|
||
return $url;
|
||
} else {
|
||
return response([], 404);
|
||
}
|
||
}
|
||
//}
|
||
|
||
|
||
}
|
||
|
||
public function removeJson(Request $request, string $tableName) {
|
||
$u = u();
|
||
$id = $request['module'];
|
||
|
||
$okPermission = false;
|
||
|
||
if(is_null($id))
|
||
{
|
||
$okPermission = true;
|
||
}
|
||
elseif(isAuth($id, "write"))
|
||
{
|
||
$okPermission = true;
|
||
}
|
||
|
||
if($okPermission) {
|
||
// Check for test_packages and test_pack_base_statuses deletion restrictions
|
||
if(($tableName == "test_packages" || $tableName == "test_pack_base_statuses")) {
|
||
$recordToDelete = db($tableName)->where("id", $request['key'])->first();
|
||
if($recordToDelete) {
|
||
$testPackageNo = null;
|
||
if($recordToDelete->is_manual == 0) {
|
||
if($tableName == "test_packages") {
|
||
$testPackageNo = $recordToDelete->test_package_number;
|
||
} elseif($tableName == "test_pack_base_statuses") {
|
||
$testPackageNo = $recordToDelete->test_package_no;
|
||
}
|
||
|
||
if($testPackageNo) {
|
||
// Check if there are any weld_logs records with this test_package_no
|
||
$weldLogsCount = db("weld_logs")
|
||
->where("test_package_no", $testPackageNo)
|
||
->count();
|
||
|
||
if($weldLogsCount > 0) {
|
||
return false; // Cannot delete - weld_logs records exist
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|
||
|
||
if($tableName == "weld_logs") {
|
||
$rawData = db("weld_logs")->where("id", $request['key'])->first();
|
||
$data = (Array) $rawData;
|
||
|
||
if($rawData) {
|
||
$data['deleted_date'] = simdi();
|
||
unset($data['id']);
|
||
db("deleted_joints")->insert($data);
|
||
}
|
||
db("repair_logs")
|
||
->where([
|
||
'new_joint_no' => $data['no_of_the_joint_as_per_as_built_survey'],
|
||
'iso_number' => $data['iso_number']
|
||
])
|
||
->delete();
|
||
|
||
db("repair_logs")
|
||
->where([
|
||
'no_of_the_joint_as_per_as_built_survey' => $data['no_of_the_joint_as_per_as_built_survey'],
|
||
'iso_number' => $data['iso_number']
|
||
])
|
||
->delete();
|
||
}
|
||
|
||
$logTestTypes = log_test_types();
|
||
$logTables = array_values($logTestTypes);
|
||
$logTypes = array_keys($logTestTypes);
|
||
$weldlogAcceptedColumns = weldlog_accepted_columns();
|
||
|
||
foreach($logTestTypes AS $logTestType => $logTable) {
|
||
if($tableName == $logTable) {
|
||
$data = db($tableName)->where("id", $request['key'])->first();
|
||
|
||
$whereData = [
|
||
'welding_date' => $data->welding_date,
|
||
'iso_number' => $data->iso_number,
|
||
'no_of_the_joint_as_per_as_built_survey' => $data->no_of_the_joint_as_per_as_built_survey
|
||
];
|
||
$updateData = [];
|
||
|
||
foreach($data AS $column => $value) {
|
||
if(in_array($column, $weldlogAcceptedColumns)) {
|
||
|
||
$updateData[$column] = null;
|
||
}
|
||
}
|
||
|
||
// PWHT özel durumu - kayıt silme
|
||
if($tableName == "p_w_h_t_s") {
|
||
$updateData['pwht_operator_id'] = null;
|
||
$updateData['pwht_operator_name'] = null;
|
||
}
|
||
/*
|
||
if($tableName == "ferrits") {
|
||
$updateData['ferrite_result'] = $updateData['result_ferrite'];
|
||
unset($updateData['result_ferrite']);
|
||
}
|
||
*/
|
||
|
||
|
||
// The following columns will be set to null in weld_logs table for the deleted record:
|
||
// Columns: " . implode(', ', array_keys($updateData))
|
||
// Log the columns being set to null and include the $data variable for debugging
|
||
Log::debug("Removing NDT data from $tableName to weld_logs. Columns set to null: " . implode(', ', array_keys($updateData)) . ". whereData: " . json_encode($whereData));
|
||
|
||
$affected = db("weld_logs")->where($whereData)->update($updateData);
|
||
Log::debug("Removing NDT data affected updated rows (weldlogs): " . $affected);
|
||
|
||
dispatchCacheBladeViews([
|
||
[
|
||
'view' => 'admin-ajax.repair-log-no-cache',
|
||
'cache' => 'repair-log'
|
||
],
|
||
]);
|
||
}
|
||
}
|
||
|
||
$oldData = db($tableName)->where("id", $request['key'])->first();
|
||
|
||
$path = "app/Http/Controllers/DeleteTrigger/$tableName.php";
|
||
|
||
if(file_exists($path)) {
|
||
include($path);
|
||
}
|
||
|
||
$this->updateSpoolStatusIfNeeded($oldData);
|
||
|
||
return db($tableName)
|
||
->where("id", $request['key'])
|
||
->delete();
|
||
} else {
|
||
return "permission error";
|
||
}
|
||
|
||
}
|
||
|
||
public function dateColumnFixer($columnName, $columnValue, $columnType) {
|
||
if($columnType == "date") {
|
||
if($columnValue == "") {
|
||
$columnValue = null;
|
||
} else {
|
||
$columnValue = preg_replace('/\(.*$/', '', $columnValue);
|
||
$carbonTarih = Carbon::parse($columnValue);
|
||
$columnValue = $carbonTarih->toDateString();
|
||
|
||
if(rejected_date($columnValue)) {
|
||
$columnValue = null;
|
||
}
|
||
}
|
||
} else {
|
||
//başlangıç tarafında bir tab girişi vs. varsa onu temizliyoruz
|
||
$columnValue = str_replace('\t', '', $columnValue);
|
||
}
|
||
|
||
|
||
|
||
return $columnValue;
|
||
}
|
||
|
||
public function isNowAuth(Request $request, $tableName) {
|
||
Log::debug('isNowAuth.start', [
|
||
'table_name' => $tableName,
|
||
'request_key' => $request['key'] ?? null,
|
||
'request_values' => $request['values'] ?? null
|
||
]);
|
||
|
||
if($tableName=="weld_logs")
|
||
{
|
||
$query = db($tableName)->where($request['key'])->first();
|
||
|
||
Log::debug('isNowAuth.query.result', [
|
||
'query_found' => !is_null($query),
|
||
'query_id' => $query->id ?? null
|
||
]);
|
||
|
||
if($query)
|
||
{
|
||
// Check if welder fields are being updated in the new data
|
||
if(isset($request['values'])) {
|
||
$newValues = $request['values'];
|
||
|
||
// Check if user is in exception levels (can bypass welder restrictions)
|
||
$u = u();
|
||
$isExceptLevel = in_array($u->level, $this->weldLogEditTimeLimitExceptLevels);
|
||
|
||
Log::debug('isNowAuth.level_exception_check', [
|
||
'user_level' => $u->level,
|
||
'is_except_level' => $isExceptLevel,
|
||
'except_levels' => $this->weldLogEditTimeLimitExceptLevels
|
||
]);
|
||
|
||
// Only apply welder restrictions if user is NOT in exception levels
|
||
if(!$isExceptLevel) {
|
||
Log::debug('isNowAuth.welder_check.existing_values', [
|
||
'welder_1' => $query->welder_1,
|
||
'welder_2' => $query->welder_2,
|
||
'welder_1_empty' => empty($query->welder_1),
|
||
'welder_2_empty' => empty($query->welder_2)
|
||
]);
|
||
|
||
Log::debug('isNowAuth.welder_check.new_values', [
|
||
'welder_1_isset' => isset($newValues['welder_1']),
|
||
'welder_2_isset' => isset($newValues['welder_2']),
|
||
'welder_1' => $newValues['welder_1'] ?? null,
|
||
'welder_2' => $newValues['welder_2'] ?? null
|
||
]);
|
||
|
||
// Check if welder fields are already filled in existing data and being updated
|
||
// If welder is filled, block immediately (no time limit exception)
|
||
if(isset($newValues['welder_1']) && !empty($query->welder_1)) {
|
||
Log::debug('isNowAuth.welder_check.blocked', [
|
||
'reason' => 'welder_1_already_filled',
|
||
'existing_value' => $query->welder_1,
|
||
'new_value' => $newValues['welder_1']
|
||
]);
|
||
return false; // Block update if welder_1 is already filled in database
|
||
}
|
||
|
||
if(isset($newValues['welder_2']) && !empty($query->welder_2)) {
|
||
Log::debug('isNowAuth.welder_check.blocked', [
|
||
'reason' => 'welder_2_already_filled',
|
||
'existing_value' => $query->welder_2,
|
||
'new_value' => $newValues['welder_2']
|
||
]);
|
||
return false; // Block update if welder_2 is already filled in database
|
||
}
|
||
} else {
|
||
Log::debug('isNowAuth.welder_check.bypassed', [
|
||
'reason' => 'user_in_exception_levels',
|
||
'user_level' => $u->level
|
||
]);
|
||
}
|
||
|
||
// If welder_1 or welder_2 is being filled for the first time (not empty), allow it
|
||
// But if they were empty and now being filled, this is allowed (first time entry)
|
||
|
||
// If only real_welder_1 or real_welder_2 is being updated, check conditions
|
||
$isOnlyRealWelderUpdate = $this->isOnlyRealWelderFieldsUpdate($newValues);
|
||
|
||
Log::debug('isNowAuth.real_welder_check.status', [
|
||
'is_only_real_welder_update' => $isOnlyRealWelderUpdate
|
||
]);
|
||
|
||
if($isOnlyRealWelderUpdate) {
|
||
// Check if corresponding welder fields are filled
|
||
$welderFieldsFilled = !empty($query->welder_1) || !empty($query->welder_2);
|
||
|
||
Log::debug('isNowAuth.real_welder_check.welder_status', [
|
||
'welder_1_value' => $query->welder_1,
|
||
'welder_2_value' => $query->welder_2,
|
||
'welder_fields_filled' => $welderFieldsFilled
|
||
]);
|
||
|
||
if(!$welderFieldsFilled) {
|
||
// If welder fields are not filled, allow real_welder update without time limit
|
||
Log::debug('isNowAuth.real_welder_check.decision', [
|
||
'action' => 'allow_without_time_limit',
|
||
'reason' => 'welder_fields_empty'
|
||
]);
|
||
return true;
|
||
}
|
||
// If welder fields are filled, continue with normal flow (time limit will be checked below)
|
||
Log::debug('isNowAuth.real_welder_check.decision', [
|
||
'action' => 'continue_to_time_check',
|
||
'reason' => 'welder_fields_filled'
|
||
]);
|
||
}
|
||
}
|
||
|
||
if($query->welding_date != "")
|
||
{
|
||
$onlyUpdateLevels = $this->weldLogEditTimeLimitExceptLevels;
|
||
$u = u();
|
||
|
||
Log::debug('isNowAuth.level_check.status', [
|
||
'user_id' => $u->id ?? null,
|
||
'user_level' => $u->level ?? null,
|
||
'allowed_levels' => $onlyUpdateLevels,
|
||
'level_in_allowed' => in_array($u->level ?? null, $onlyUpdateLevels)
|
||
]);
|
||
|
||
if(in_array($u->level, $onlyUpdateLevels))
|
||
{
|
||
Log::debug('isNowAuth.level_check.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'user_level_in_exception_list',
|
||
'user_level' => $u->level
|
||
]);
|
||
return true;
|
||
|
||
} else {
|
||
Log::debug('isNowAuth.time_limit_check.initiating', [
|
||
'user_level' => $u->level,
|
||
'welding_date' => $query->welding_date,
|
||
'created_at' => $query->created_at
|
||
]);
|
||
return $this->checkWeldLogTimeLimit($query);
|
||
}
|
||
} else {
|
||
Log::debug('isNowAuth.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'welding_date_empty'
|
||
]);
|
||
return true;
|
||
}
|
||
}
|
||
} else {
|
||
Log::debug('isNowAuth.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'not_weld_logs_table',
|
||
'table_name' => $tableName
|
||
]);
|
||
return true;
|
||
}
|
||
|
||
}
|
||
|
||
/**
|
||
* Check if only real_welder_1 or real_welder_2 fields are being updated
|
||
*/
|
||
private function isOnlyRealWelderFieldsUpdate($values) {
|
||
$realWelderFields = ['real_welder_1', 'real_welder_2'];
|
||
$updatingFields = array_keys($values);
|
||
|
||
// Check if any real_welder field is being updated
|
||
$hasRealWelderUpdate = !empty(array_intersect($updatingFields, $realWelderFields));
|
||
|
||
// Check if only real_welder fields are being updated (no other fields)
|
||
$otherFields = array_diff($updatingFields, $realWelderFields);
|
||
$isOnlyRealWelderUpdate = $hasRealWelderUpdate && empty($otherFields);
|
||
|
||
Log::debug('isOnlyRealWelderFieldsUpdate.analysis', [
|
||
'updating_fields' => $updatingFields,
|
||
'has_real_welder_update' => $hasRealWelderUpdate,
|
||
'other_fields' => $otherFields,
|
||
'is_only_real_welder_update' => $isOnlyRealWelderUpdate,
|
||
'real_welder_field_values' => [
|
||
'real_welder_1' => $values['real_welder_1'] ?? null,
|
||
'real_welder_2' => $values['real_welder_2'] ?? null
|
||
]
|
||
]);
|
||
|
||
return $isOnlyRealWelderUpdate;
|
||
}
|
||
|
||
/**
|
||
* Update spool status if iso_number exists in data
|
||
*/
|
||
private function updateSpoolStatusIfNeeded($data) {
|
||
$isoNumber = $data->iso_number ?? $data->line_no ?? $data->line_number ?? null;
|
||
$spoolNumber = $data->spool_number ?? null;
|
||
|
||
if ($isoNumber !== null) {
|
||
\App\Jobs\SpoolStatusChangerJob::dispatch($isoNumber, $spoolNumber);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Check if restricted columns are filled before allowing save
|
||
* Returns true if save is allowed, false if restricted
|
||
*/
|
||
private function checkRestrictedColumnsBeforeSave($tableName, $recordId) {
|
||
$u = u();
|
||
|
||
// If user level is in exception list, allow save
|
||
if(in_array($u->level, $this->weldLogEditTimeLimitExceptLevels)) {
|
||
Log::debug('checkRestrictedColumns.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'user_level_in_exception_list',
|
||
'user_level' => $u->level
|
||
]);
|
||
return true;
|
||
}
|
||
|
||
// For weld_logs: lock trigger is specifically welder_1 and welder_2 being filled
|
||
// Other fields like vt_result being filled should NOT lock the record
|
||
if($tableName != 'weld_logs') {
|
||
Log::debug('checkRestrictedColumns.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'table_not_weld_logs',
|
||
'table_name' => $tableName
|
||
]);
|
||
return true;
|
||
}
|
||
|
||
// Get the record to check
|
||
$record = db($tableName)->find($recordId);
|
||
|
||
if(!$record) {
|
||
Log::debug('checkRestrictedColumns.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'record_not_found',
|
||
'table_name' => $tableName,
|
||
'record_id' => $recordId
|
||
]);
|
||
return true;
|
||
}
|
||
|
||
// Lock trigger: welder_1 or welder_2 being filled
|
||
$welder1Filled = !empty($record->welder_1);
|
||
$welder2Filled = !empty($record->welder_2);
|
||
|
||
Log::debug('checkRestrictedColumns.welder_status', [
|
||
'welder_1_filled' => $welder1Filled,
|
||
'welder_2_filled' => $welder2Filled,
|
||
'welder_1_value' => $record->welder_1,
|
||
'welder_2_value' => $record->welder_2,
|
||
'record_id' => $recordId
|
||
]);
|
||
|
||
// If welder_1 or welder_2 is filled, lock the record immediately
|
||
if($welder1Filled || $welder2Filled) {
|
||
Log::warning('checkRestrictedColumns.decision', [
|
||
'action' => 'deny',
|
||
'reason' => 'welder_fields_filled_record_locked',
|
||
'table_name' => $tableName,
|
||
'record_id' => $recordId,
|
||
'user_level' => $u->level,
|
||
'welder_1_filled' => $welder1Filled,
|
||
'welder_2_filled' => $welder2Filled
|
||
]);
|
||
return false;
|
||
}
|
||
|
||
// welder_1 and welder_2 are both empty - 4 hour time limit continues
|
||
Log::debug('checkRestrictedColumns.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'welder_fields_empty_time_limit_active',
|
||
'table_name' => $tableName,
|
||
'record_id' => $recordId
|
||
]);
|
||
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* Check weld log time limit for updates
|
||
*/
|
||
private function checkWeldLogTimeLimit($query) {
|
||
Log::debug('checkWeldLogTimeLimit.start', [
|
||
'query_id' => $query->id ?? null,
|
||
'updated_at' => $query->updated_at,
|
||
'updated_at_is_null' => is_null($query->updated_at)
|
||
]);
|
||
|
||
$columnCommentDate = ColumnComment::where('table_name', 'weld_logs')
|
||
->where('record_id', $query->id)
|
||
->where('column_name', 'welding_date')
|
||
->where(function ($q) {
|
||
$q->where('comment', 'LIKE', '%Welding date set%');
|
||
})
|
||
->orderBy('created_at', 'DESC')
|
||
->value('created_at');
|
||
|
||
$gecmisTarih = null;
|
||
$dateSource = null;
|
||
|
||
if(!is_null($columnCommentDate)) {
|
||
$gecmisTarih = Carbon::parse($columnCommentDate);
|
||
$dateSource = 'column_comment';
|
||
} elseif(!is_null($query->updated_at)) {
|
||
$gecmisTarih = Carbon::parse($query->updated_at);
|
||
$dateSource = 'updated_at';
|
||
}
|
||
|
||
Log::debug('checkWeldLogTimeLimit.date_source', [
|
||
'record_id' => $query->id ?? null,
|
||
'column_comment_found' => !is_null($columnCommentDate),
|
||
'column_comment_created_at' => $columnCommentDate,
|
||
'updated_at' => $query->updated_at,
|
||
'date_source' => $dateSource
|
||
]);
|
||
|
||
if(!is_null($gecmisTarih))
|
||
{
|
||
$simdikiTarih = Carbon::now();
|
||
$izinVerilenSaatFarki = (int) setting('weld_log_edit_time_limit', false, 4); // Get hour limit from settings
|
||
|
||
// If no time limit is set, allow editing
|
||
if(empty($izinVerilenSaatFarki)) {
|
||
Log::debug('checkWeldLogTimeLimit.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'no_time_limit_set',
|
||
'hour_difference' => 0,
|
||
'allowed_limit' => 0
|
||
]);
|
||
return true;
|
||
}
|
||
|
||
$saatFarki = $gecmisTarih->diffInHours($simdikiTarih);
|
||
|
||
Log::debug('checkWeldLogTimeLimit.calculation', [
|
||
'updated_at' => $gecmisTarih->toDateTimeString(),
|
||
'current_time' => $simdikiTarih->toDateTimeString(),
|
||
'allowed_hour_limit' => $izinVerilenSaatFarki,
|
||
'actual_hour_difference' => $saatFarki,
|
||
'within_limit' => $saatFarki <= $izinVerilenSaatFarki
|
||
]);
|
||
|
||
if($saatFarki <= $izinVerilenSaatFarki)
|
||
{
|
||
Log::debug('checkWeldLogTimeLimit.decision', [
|
||
'action' => 'allow',
|
||
'reason' => 'within_time_limit',
|
||
'hour_difference' => $saatFarki,
|
||
'allowed_limit' => $izinVerilenSaatFarki
|
||
]);
|
||
return true;
|
||
} else {
|
||
Log::debug('checkWeldLogTimeLimit.decision', [
|
||
'action' => 'deny',
|
||
'reason' => 'exceeded_time_limit',
|
||
'hour_difference' => $saatFarki,
|
||
'allowed_limit' => $izinVerilenSaatFarki,
|
||
'exceeded_by' => $saatFarki - $izinVerilenSaatFarki
|
||
]);
|
||
return false;
|
||
}
|
||
} else {
|
||
Log::debug('checkWeldLogTimeLimit.decision', [
|
||
'action' => 'deny',
|
||
'reason' => 'no_valid_date_source'
|
||
]);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Belirli tablolar için sadece izin verilen alanların güncellenip güncellenmediğini kontrol eder
|
||
* Eğer sadece izin verilen alanlar güncelleniyorsa true döner
|
||
*/
|
||
private function isOnlyAllowedFieldsUpdate(Request $request, $tableName) {
|
||
// İzin verilen alanları tablo bazında tanımla
|
||
$allowedFieldsForTables = [
|
||
'weld_logs' => ['test_package_no'],
|
||
'line_list' => ['external_finish_type', 'paint_cycle'],
|
||
// Buraya diğer tablolar ve alanları eklenebilir
|
||
];
|
||
|
||
// Eğer güncellenecek veri yoksa false döner
|
||
if(!isset($request['values']) || empty($request['values'])) {
|
||
return false;
|
||
}
|
||
|
||
// Eğer bu tablo için izin verilen alanlar tanımlanmamışsa false döner
|
||
if(!isset($allowedFieldsForTables[$tableName])) {
|
||
return false;
|
||
}
|
||
|
||
$updateData = $request['values'];
|
||
$updateFields = array_keys($updateData);
|
||
$allowedFields = $allowedFieldsForTables[$tableName];
|
||
|
||
// Güncellenecek alanların hepsi izin verilen alanlar içinde mi kontrol et
|
||
foreach($updateFields as $field) {
|
||
if(!in_array($field, $allowedFields)) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// En az bir alan güncelleniyor ve hepsi izin verilen alanlar içinde
|
||
return count($updateFields) > 0;
|
||
}
|
||
|
||
/**
|
||
* Handover tablosu için özel veri işleme
|
||
* Controller alanları doluysa, aynı controller değerine sahip diğer satırlardaki boş controller alanlarını günceller
|
||
*/
|
||
private function processHandoverData($data) {
|
||
// Handover control count'u ayarlardan al
|
||
$handoverControlCount = (int) setting('handover_control_count', 3);
|
||
|
||
// Her control için kontrol et
|
||
for ($i = 1; $i <= $handoverControlCount; $i++) {
|
||
$controllerField = "control{$i}_controller";
|
||
|
||
// Eğer controller alanı doluysa ve değişiklik yapıldıysa
|
||
if (isset($data[$controllerField]) && !empty($data[$controllerField])) {
|
||
$controllerValue = $data[$controllerField];
|
||
|
||
// Aynı controller değerine sahip diğer satırlardaki boş controller alanlarını güncelle
|
||
$updateData = [
|
||
$controllerField => $controllerValue,
|
||
'final_status' => $controllerValue
|
||
];
|
||
|
||
// Controller alanı boş olan satırları bul ve güncelle
|
||
db('handovers')
|
||
->where($controllerField, '')
|
||
->orWhereNull($controllerField)
|
||
->update($updateData);
|
||
}
|
||
}
|
||
|
||
return $data;
|
||
}
|
||
|
||
/**
|
||
* Send notifications based on table operations
|
||
* Performance: Only sends if notification settings are configured
|
||
*/
|
||
private function sendTableNotification($tableName, $recordId, $data, $action = 'insert') {
|
||
try {
|
||
// Table-specific notification logic
|
||
switch($tableName) {
|
||
case 'weld_maps':
|
||
if($action == 'insert') {
|
||
$parts = [];
|
||
if(!empty($data['line_number'])) $parts[] = "Line: {$data['line_number']}";
|
||
if(!empty($data['spool_number'])) $parts[] = "Spool: {$data['spool_number']}";
|
||
$message = !empty($parts) ? implode(', ', $parts) : "New weld map record has been created";
|
||
$link = url("/admin/types/weld-map?id={$recordId}");
|
||
sendNotification('notification_new_weld_map', $message, $link, 'New Weld Map Record');
|
||
}
|
||
break;
|
||
|
||
case 'n_c_r_logs':
|
||
if($action == 'insert') {
|
||
$message = !empty($data['ncr_no'])
|
||
? "NCR {$data['ncr_no']} has been created"
|
||
: "New NCR record has been created";
|
||
$link = url("/admin/types/ncr?id={$recordId}");
|
||
sendNotification('notification_new_ncr', $message, $link, 'New NCR Created');
|
||
}
|
||
break;
|
||
|
||
case 'r_f_i_s':
|
||
if($action == 'insert') {
|
||
$parts = [];
|
||
if(!empty($data['rfi_no'])) $parts[] = "RFI {$data['rfi_no']}";
|
||
if(!empty($data['subject'])) $parts[] = $data['subject'];
|
||
$message = !empty($parts) ? implode(' - ', $parts) : "New RFI has been created";
|
||
$link = url("/admin/types/rfi?id={$recordId}");
|
||
sendNotification('notification_new_rfi', $message, $link, 'New RFI Created');
|
||
}
|
||
break;
|
||
|
||
case 'test_packages':
|
||
if($action == 'insert') {
|
||
$message = !empty($data['test_pack_number'])
|
||
? "Test Package {$data['test_pack_number']} is ready"
|
||
: "New test package is ready";
|
||
$link = url("/admin/types/test-package?id={$recordId}");
|
||
sendNotification('notification_test_package_ready', $message, $link, 'Test Package Ready');
|
||
}
|
||
break;
|
||
|
||
case 'radiographic_tests':
|
||
case 'ultrasonic_tests':
|
||
case 'magnetic_tests':
|
||
case 'dye_penetrant_tests':
|
||
if($action == 'insert') {
|
||
$testType = strtoupper(str_replace('_tests', '', str_replace('_', ' ', $tableName)));
|
||
$jointNumber = $data['no_of_the_joint_as_per_as_built_survey'] ?? null;
|
||
$message = $jointNumber
|
||
? "{$testType} test completed for Joint {$jointNumber}"
|
||
: "{$testType} test has been completed";
|
||
$link = url("/admin/types/{$tableName}?id={$recordId}");
|
||
sendNotification('notification_ndt_completed', $message, $link, 'NDT Test Completed');
|
||
}
|
||
break;
|
||
|
||
case 'incoming_controls':
|
||
if($action == 'insert') {
|
||
$parts = [];
|
||
if(!empty($data['material_name'])) $parts[] = $data['material_name'];
|
||
if(!empty($data['certificate_no'])) $parts[] = "Cert: {$data['certificate_no']}";
|
||
if(!empty($data['heat_number'])) $parts[] = "Heat: {$data['heat_number']}";
|
||
|
||
$message = !empty($parts)
|
||
? implode(' | ', $parts)
|
||
: "New incoming control record has been created";
|
||
$link = url("/admin/types/incoming-control?id={$recordId}");
|
||
sendNotification('notification_new_incoming_control', $message, $link, 'New Incoming Control');
|
||
}
|
||
break;
|
||
}
|
||
} catch (\Exception $e) {
|
||
// Log error but don't break the main flow
|
||
\Log::error('Notification send error in AdminController: ' . $e->getMessage());
|
||
}
|
||
}
|
||
|
||
private function trimData($data) {
|
||
$refactoringData = [];
|
||
foreach($data AS $columnName => $columnValue) {
|
||
if (is_null($columnValue) || $columnValue === "") {
|
||
$refactoringData[$columnName] = null;
|
||
continue;
|
||
}
|
||
|
||
// Eğer string ise trim uygula
|
||
if (is_string($columnValue)) {
|
||
$columnValue = trim($columnValue);
|
||
}
|
||
|
||
$columnType = table_column_type($this->currentTable, $columnName);
|
||
$refactoringData[$columnName] = $this->dateColumnFixer($columnName, $columnValue, $columnType);
|
||
}
|
||
return $refactoringData;
|
||
}
|
||
|
||
public function weldingDateFiller($beforeData, $data, $id, $tableName) {
|
||
// Add column comment when welding_date transitions from empty to filled
|
||
if (!is_null($beforeData)) {
|
||
$previousWeldingDate = $beforeData->welding_date ?? null;
|
||
$currentWeldingDate = $data['welding_date'] ?? null;
|
||
Log::info("Welding date column comment checking", [
|
||
'weld_log_id' => $id,
|
||
'previous_welding_date' => $previousWeldingDate,
|
||
'current_welding_date' => $currentWeldingDate
|
||
]);
|
||
$user = u();
|
||
$userName = $user;
|
||
|
||
if (empty($previousWeldingDate) && !empty($currentWeldingDate)) {
|
||
|
||
|
||
ColumnComment::create([
|
||
'table_name' => $tableName,
|
||
'record_id' => $id,
|
||
'column_name' => 'welding_date',
|
||
'comment' => "Welding date set",
|
||
'column_value' => $currentWeldingDate,
|
||
'user_id' => $user->id ?? null,
|
||
'ip_address' => request()->ip()
|
||
]);
|
||
|
||
Log::info("Welding date column comment created", [
|
||
'weld_log_id' => $id,
|
||
'welding_date' => $currentWeldingDate,
|
||
'user' => $userName
|
||
]);
|
||
} else {
|
||
Log::info("Welding date column comment not created", [
|
||
'weld_log_id' => $id,
|
||
'previous_welding_date' => $previousWeldingDate,
|
||
'current_welding_date' => $currentWeldingDate,
|
||
'user' => $userName
|
||
]);
|
||
}
|
||
} else {
|
||
Log::info("Welding date column comment not created", [
|
||
'weld_log_id' => $id,
|
||
'previous_welding_date' => $previousWeldingDate,
|
||
'current_welding_date' => $currentWeldingDate,
|
||
'user' => $userName
|
||
]);
|
||
}
|
||
}
|
||
|
||
public function saveJson(Request $request, string $tableName) {
|
||
$this->currentTable = $tableName; // tableName'i sınıf içinde saklıyoruz
|
||
if(!is_array($request['key']))
|
||
{
|
||
$request['key'] = ['id' => $request['key']];
|
||
}
|
||
|
||
// Initialize saveAllowedFields to prevent undefined variable error
|
||
$saveAllowedFields = false;
|
||
|
||
if(getesit("module","manage-ndt")) {
|
||
$saveAccept = true;
|
||
} else {
|
||
// Check if only allowed fields are being updated
|
||
if($this->isOnlyAllowedFieldsUpdate($request, $tableName)) {
|
||
$saveAccept = true;
|
||
$saveAllowedFields = true;
|
||
} else {
|
||
$saveAccept = $this->isNowAuth($request, $tableName);
|
||
}
|
||
|
||
}
|
||
|
||
// Check restricted columns before save (applies to all users except exception levels)
|
||
if($saveAccept && !$saveAllowedFields) {
|
||
$recordId = $request['key']['id'] ?? null;
|
||
if($recordId) {
|
||
$restrictedCheck = $this->checkRestrictedColumnsBeforeSave($tableName, $recordId);
|
||
if(!$restrictedCheck) {
|
||
Log::warning('saveJson.restricted_columns_check_failed', [
|
||
'table_name' => $tableName,
|
||
'record_id' => $recordId,
|
||
'user_id' => u()->id,
|
||
'user_level' => u()->level
|
||
]);
|
||
echo "restricted_columns_filled";
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
if($saveAccept)
|
||
{
|
||
$updateData = $request['values'];
|
||
$refactoringData = $this->trimData($updateData);
|
||
$refactoringData['updated_at'] = Carbon::now();
|
||
|
||
// Handover tablosu için özel kontrol
|
||
if($tableName == "handovers") {
|
||
$refactoringData = $this->processHandoverData($refactoringData);
|
||
}
|
||
|
||
$beforeData = db($tableName)->where($request['key'])->first();
|
||
|
||
try {
|
||
$result = db($tableName)
|
||
->where($request['key'])
|
||
->update($refactoringData);
|
||
|
||
|
||
// Değişiklikleri ColumnComment tablosuna kaydedelim
|
||
if($result) {
|
||
$record_id = isset($request['key']['id']) ? $request['key']['id'] : $beforeData->id;
|
||
|
||
// Her değişiklik için bir kayıt ekleyelim
|
||
foreach($refactoringData as $column => $value) {
|
||
// Bazı sütunları atlayalım (updated_at, created_at, deleted_at)
|
||
if(in_array($column, ['updated_at', 'created_at', 'deleted_at'])) {
|
||
continue;
|
||
}
|
||
|
||
// Önceki değeri alalım
|
||
$oldValue = isset($beforeData->$column) ? $beforeData->$column : null;
|
||
|
||
// Değer değişmişse kaydet
|
||
if($oldValue != $value) {
|
||
ColumnComment::create([
|
||
'table_name' => $tableName,
|
||
'record_id' => $record_id,
|
||
'column_name' => $column,
|
||
'comment' => 'System updated the value',
|
||
'column_value' => $value,
|
||
'user_id' => u()->id,
|
||
'ip_address' => $request->ip()
|
||
]);
|
||
|
||
// Document Revision REV number changed - send notification
|
||
if($tableName == 'document_revisions' && $column == 'revision_no' && $oldValue !== null && $oldValue !== '') {
|
||
$drawingNo = $beforeData->drawing_no ?? 'Unknown';
|
||
$message = sprintf(
|
||
'Document Revision REV changed from %s to %s for Drawing %s. Please update PDF files.',
|
||
$oldValue,
|
||
$value,
|
||
$drawingNo
|
||
);
|
||
$link = "/admin/types/document-revision?id={$record_id}";
|
||
sendNotification('notification_document_revision_changed', $message, $link, 'Document REV Changed');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
} catch (\Throwable $th) {
|
||
$result = $th->getMessage();
|
||
}
|
||
|
||
|
||
if(in_array($tableName, log_test_types())) {
|
||
$data = db($tableName)->where($request['key'])->first();
|
||
logToWeldlogUpdate($data);
|
||
logToWPQUpdate($data, $tableName);
|
||
|
||
// PWHT verilerinin doğrudan aktarımı
|
||
if($tableName == "p_w_h_t_s") {
|
||
$whereData = [
|
||
'iso_number' => $data->iso_number,
|
||
'no_of_the_joint_as_per_as_built_survey' => $data->no_of_the_joint_as_per_as_built_survey,
|
||
'welding_date' => $data->welding_date,
|
||
];
|
||
|
||
$updateData = [];
|
||
|
||
// PWHT operatör verileri özel olarak güncelleniyor
|
||
if(isset($data->pwht_operator_id)) {
|
||
$updateData['pwht_operator_id'] = $data->pwht_operator_id;
|
||
}
|
||
|
||
if(isset($data->pwht_operator)) {
|
||
$updateData['pwht_operator_name'] = $data->pwht_operator;
|
||
}
|
||
|
||
if(!empty($updateData)) {
|
||
db("weld_logs")->where($whereData)->update($updateData);
|
||
}
|
||
}
|
||
|
||
dispatchCacheBladeViews([
|
||
[
|
||
'view' => 'admin-ajax.request-ndt-no-cache',
|
||
'cache' => 'request-ndt'
|
||
],
|
||
]);
|
||
}
|
||
|
||
// Get updated data for spool status check
|
||
$updatedData = db($tableName)->where($request['key'])->first();
|
||
//$this->updateSpoolStatusIfNeeded($updatedData);
|
||
|
||
if($tableName == "weld_logs") {
|
||
$this->weldingDateFiller($beforeData, $refactoringData, $record_id, $tableName);
|
||
materialGroupUpdater($request['key']['id']);
|
||
}
|
||
//syncTrigger($tableName, $beforeData->id);
|
||
|
||
|
||
|
||
// SaveTrigger'ı asenkron olarak çalıştır
|
||
ExecuteSaveTriggerJob::dispatch(
|
||
$tableName,
|
||
$request->all(),
|
||
$request['key'],
|
||
$request['values'] ?? null,
|
||
$beforeData,
|
||
"update"
|
||
);
|
||
|
||
|
||
|
||
|
||
|
||
} else {
|
||
Log::info("isNowAuth.Weld log edit time limit");
|
||
echo "weld_log_edit_time_limit";
|
||
}
|
||
|
||
}
|
||
|
||
|
||
public function insertJson(Request $request, string $tableName) {
|
||
$this->currentTable = $tableName; // tableName'i sınıf içinde saklıyoruz
|
||
$data = $_POST;
|
||
unset($data['_token']);
|
||
|
||
$refactoringData = $this->trimData($data);
|
||
unset($refactoringData['id']);
|
||
$refactoringData['created_at'] = Carbon::now();
|
||
|
||
// Handover tablosu için özel kontrol
|
||
if($tableName == "handovers") {
|
||
$refactoringData = $this->processHandoverData($refactoringData);
|
||
}
|
||
|
||
if($tableName == "test_pack_base_statuses" || $tableName == "test_packages") {
|
||
$refactoringData['is_manual'] = 1;
|
||
}
|
||
|
||
if($tableName == "m_t_o_s") {
|
||
if(!db($tableName)->where([
|
||
'line' => $refactoringData['line'],
|
||
'component_code_id' => $refactoringData['component_code_id'],
|
||
])->first()) {
|
||
$id = db($tableName)->insertGetId($data);
|
||
} else {
|
||
echo false;
|
||
}
|
||
|
||
|
||
} elseif($tableName == "weld_logs") {
|
||
|
||
$exists = db($tableName)
|
||
->where("iso_number", $refactoringData['iso_number'])
|
||
->where("no_of_the_joint_as_per_as_built_survey", $refactoringData['no_of_the_joint_as_per_as_built_survey'])
|
||
->first();
|
||
|
||
// dd($exists);
|
||
if(!$exists) {
|
||
$id = db($tableName)->insertGetId($refactoringData);
|
||
|
||
// Send notification for new weld log record
|
||
$parts = [];
|
||
if(!empty($refactoringData['no_of_the_joint_as_per_as_built_survey'])) {
|
||
$parts[] = "Joint: {$refactoringData['no_of_the_joint_as_per_as_built_survey']}";
|
||
}
|
||
if(!empty($refactoringData['spool_number'])) {
|
||
$parts[] = "Spool: {$refactoringData['spool_number']}";
|
||
}
|
||
if(!empty($refactoringData['iso_number'])) {
|
||
$parts[] = "ISO: {$refactoringData['iso_number']}";
|
||
}
|
||
$message = !empty($parts) ? implode(' | ', $parts) : "New weld log record has been created";
|
||
$link = url("/admin/types/weld-log?id={$id}");
|
||
sendNotification('notification_new_weld_log', $message, $link, 'New Weld Log Record');
|
||
} else {
|
||
//dd("already");
|
||
echo false;
|
||
}
|
||
|
||
materialGroupUpdater($id);
|
||
|
||
|
||
} elseif($tableName == "nde_matrices") {
|
||
if(!db($tableName)->where([
|
||
'line' => $refactoringData['line'],
|
||
'type_of_joint' => $refactoringData['type_of_joint'],
|
||
])->first()) {
|
||
$id = db($tableName)->insertGetId($data);
|
||
} else {
|
||
echo false;
|
||
}
|
||
} elseif($tableName == "naks_welders") {
|
||
$id = db($tableName)->insertGetId($refactoringData);
|
||
|
||
// Send notification for new NAKS Welder ID Card creation
|
||
$welderName = $refactoringData['welder_name_en'] ?? $refactoringData['welder_name_ru'] ?? 'Unknown Welder';
|
||
$welderId = $refactoringData['welder_id'] ?? $refactoringData['naks_certificate_no'] ?? $id;
|
||
$message = "New Welder ID Card created for {$welderName} (Welder ID: {$welderId})";
|
||
$link = url("/admin/types/welder-id-cart?welder_id=" . urlencode($welderId));
|
||
sendNotification('notification_welder_id_card_created', $message, $link, 'Welder ID Card Created');
|
||
} elseif($tableName == "welding_equipment") {
|
||
$id = db($tableName)->insertGetId($refactoringData);
|
||
} elseif(in_array($tableName, log_test_types())) {
|
||
$id = db($tableName)->insertGetId($refactoringData);
|
||
$data = db($tableName)->where("id", $id)->first();
|
||
logToWeldlogUpdate($data);
|
||
logToWPQUpdate($data, $tableName);
|
||
|
||
// PWHT verilerinin doğrudan aktarımı - yeni kayıt için
|
||
if($tableName == "p_w_h_t_s") {
|
||
$whereData = [
|
||
'iso_number' => $data->iso_number,
|
||
'no_of_the_joint_as_per_as_built_survey' => $data->no_of_the_joint_as_per_as_built_survey,
|
||
'welding_date' => $data->welding_date,
|
||
];
|
||
|
||
$updateData = [];
|
||
|
||
// PWHT operatör verileri özel olarak güncelleniyor
|
||
if(isset($data->pwht_operator_id)) {
|
||
$updateData['pwht_operator_id'] = $data->pwht_operator_id;
|
||
}
|
||
|
||
if(isset($data->pwht_operator)) {
|
||
$updateData['pwht_operator_name'] = $data->pwht_operator;
|
||
}
|
||
|
||
if(!empty($updateData)) {
|
||
db("weld_logs")->where($whereData)->update($updateData);
|
||
}
|
||
}
|
||
|
||
dispatchCacheBladeViews([
|
||
[
|
||
'view' => 'admin-ajax.request-ndt-no-cache',
|
||
'cache' => 'request-ndt'
|
||
],
|
||
]);
|
||
} else {
|
||
$id = db($tableName)->insertGetId($refactoringData);
|
||
}
|
||
|
||
if(isset($id)) {
|
||
$refactoringData['id'] = $id;
|
||
$request['key'] = ['id' => $id]; // Array formatında set et
|
||
|
||
// Yeni eklenen kayıt için ColumnComment ekleyelim
|
||
foreach($refactoringData as $column => $value) {
|
||
// Bazı sütunları atlayalım
|
||
if(in_array($column, ['created_at', 'updated_at', 'deleted_at', 'id'])) {
|
||
continue;
|
||
}
|
||
|
||
// Null olmayan ve boş string olmayan değerler için kayıt oluştur
|
||
if($value !== null && $value !== '') {
|
||
ColumnComment::create([
|
||
'table_name' => $tableName,
|
||
'record_id' => $id,
|
||
'column_name' => $column,
|
||
'comment' => 'System created the record',
|
||
'column_value' => $value,
|
||
'user_id' => u()->id,
|
||
'ip_address' => $request->ip()
|
||
]);
|
||
}
|
||
}
|
||
|
||
$beforeData = db($tableName)->where($request['key'])->first();
|
||
|
||
$this->updateSpoolStatusIfNeeded($beforeData);
|
||
|
||
// SaveTrigger'ı asenkron olarak çalıştır
|
||
ExecuteSaveTriggerJob::dispatch(
|
||
$tableName,
|
||
$request->all(),
|
||
$request['key'],
|
||
$request['values'] ?? null,
|
||
$beforeData,
|
||
"insert"
|
||
);
|
||
|
||
// Send notifications for specific table inserts
|
||
$this->sendTableNotification($tableName, $id, $refactoringData, 'insert');
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
return response()->json(
|
||
($refactoringData),
|
||
200,
|
||
[
|
||
'Content-Type' => 'application/json;charset=UTF-8',
|
||
'Charset' => 'utf-8'
|
||
],
|
||
JSON_UNESCAPED_UNICODE
|
||
);
|
||
|
||
}
|
||
|
||
private function rawSQLFixer($rawSQL) {
|
||
$replaceData = [
|
||
"`short_number-certificate_no`" => "CONCAT_WS('-',`short_number`, `certificate_no`)",
|
||
"`mat_group_1 mat_group_2`" => "CONCAT_WS(' + ',`mat_group_1`, `mat_group_2`)",
|
||
"AND ()" => "",
|
||
];
|
||
foreach($replaceData AS $from => $to ) {
|
||
$rawSQL = str_replace($from, $to, $rawSQL);
|
||
}
|
||
return $rawSQL;
|
||
}
|
||
private function sortColumnFixer($selector) {
|
||
$replaceData = [
|
||
"`short_number-certificate_no`" => "CONCAT_WS('-',`short_number`, `certificate_no`)",
|
||
"{mat_group_1} + {mat_group_2}" => "mat_group_1",
|
||
"{" => "",
|
||
"}" => "",
|
||
];
|
||
foreach($replaceData AS $from => $to ) {
|
||
$selector = str_replace($from, $to, $selector);
|
||
}
|
||
return $selector;
|
||
}
|
||
|
||
public function tableToJson(Request $request, string $tableName) {
|
||
|
||
$_SESSION['module'] = get("module");
|
||
$path = "app/Http/Controllers/CustomQuery/{$_GET['module']}.php";
|
||
|
||
if(file_exists($path)) {
|
||
include($path);
|
||
} else {
|
||
if(getesit("module","technology-summary")) { //custom table
|
||
$query = db("naks_certificates")->groupBy(
|
||
'short_number',
|
||
'certificate_no',
|
||
'welding_method',
|
||
'technology_category',
|
||
'mat_group_1',
|
||
'mat_group_2',
|
||
'work_type',
|
||
'pwht',
|
||
'valid_to',
|
||
'valid_from',
|
||
);
|
||
} else {
|
||
$query = db($tableName);
|
||
}
|
||
}
|
||
|
||
|
||
$u = u();
|
||
if($tableName == "weld_logs") {
|
||
if($u->subcontructer != setting("main_subcontractor")) {
|
||
// $query = $query->where("ste_subcontractor", $u->subcontructer);
|
||
}
|
||
|
||
// Apply employer view filters: exclude repair, reject, cut records
|
||
if(getesit("module", "weldlog-employer-view")) {
|
||
// Filter 1: Exclude records with repair_status = 'Repair' in repair_logs
|
||
$query = $query->whereNotExists(function($subQuery) {
|
||
$subQuery->select(\DB::raw(1))
|
||
->from('repair_logs')
|
||
->whereColumn('repair_logs.iso_number', 'weld_logs.iso_number')
|
||
->whereColumn('repair_logs.new_joint_no', 'weld_logs.no_of_the_joint_as_per_as_built_survey')
|
||
->where('repair_logs.repair_status', 'Repair');
|
||
});
|
||
|
||
// Filter 2: Only show records with Accept or empty/null NDT results
|
||
$ndtResultFields = ['vt_result', 'rt_result', 'ut_result', 'pt_result', 'mt_result', 'pmi_result', 'ferrite_result', 'ht_result'];
|
||
foreach($ndtResultFields as $field) {
|
||
$query = $query->where(function($q) use ($field) {
|
||
$q->whereIn($field, ['Accept / Годен', ''])
|
||
->orWhereNull($field);
|
||
});
|
||
}
|
||
}
|
||
}
|
||
if($tableName == "users") {
|
||
$jobDesc = db("job_descriptions")->get()->pluck("title")->toArray();
|
||
$jobDesc[] = null;
|
||
$jobDesc[] = "";
|
||
if(getesit("module","employees")) {
|
||
$query = $query->whereIn("level", ['Welder (Subcontractor)'])->orWhereNull("level");
|
||
}
|
||
|
||
|
||
}
|
||
|
||
if(!getisset("group")) {
|
||
if(getisset("take")) $query = $query->take(get("take"));
|
||
if(getisset("skip")) $query = $query->skip(get("skip"));
|
||
}
|
||
|
||
if(getisset("columns")) {
|
||
$selectColumns = j(get("columns"));
|
||
if(!in_array("id", $selectColumns)) {
|
||
array_unshift($selectColumns, "id");
|
||
}
|
||
$query = $query->select($selectColumns);
|
||
}
|
||
|
||
|
||
if(getisset("sort")) {
|
||
$sortColumns = j($request->sort);
|
||
foreach($sortColumns AS $sortColumn) {
|
||
$sortType = $sortColumn['desc'] == true ? "ASC" : "DESC";
|
||
$sortColumn['selector'] = $this->sortColumnFixer($sortColumn['selector']);
|
||
//dd($sortColumn);
|
||
$query = $query->orderBy($sortColumn['selector'], $sortType);
|
||
}
|
||
} else {
|
||
$query = $query->orderBy("id","DESC");
|
||
}
|
||
|
||
if(getisset("filter")) {
|
||
|
||
$filterColumns = j($request->filter);
|
||
$allFilterValues = [];
|
||
|
||
$rawSQL = FilterHelper::GetSqlExprByArray($filterColumns);
|
||
$rawSQL = $this->rawSQLFixer($rawSQL);
|
||
|
||
$query = $query->whereRaw($rawSQL);
|
||
/*
|
||
if(!is_array($filterColumns[0])) {
|
||
$allFilterValues[$filterColumns[0]][] = $filterColumns[2];
|
||
} else {
|
||
foreach($filterColumns AS $filterColumn) {
|
||
|
||
if(is_array($filterColumn)) {
|
||
$column = $filterColumn[0];
|
||
foreach($filterColumn AS $subFilterColumn) {
|
||
if(is_array($subFilterColumn)) {
|
||
$allFilterValues[$subFilterColumn[0]][] = $subFilterColumn[2];
|
||
} else {
|
||
//dump($filterColumn);
|
||
if(is_array($filterColumn[0])) {
|
||
$allFilterValues[$filterColumn[0][0]][] = $filterColumn[0][2];
|
||
}
|
||
|
||
|
||
|
||
}
|
||
|
||
}
|
||
|
||
} else {
|
||
//dump()
|
||
//$allFilterValues[$filterColumn[0]][] = $filterColumn[2];
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
foreach($allFilterValues AS $column => $values) {
|
||
if($column != null) {
|
||
$query = $query->whereIn($column, $values);
|
||
}
|
||
|
||
}
|
||
*/
|
||
|
||
|
||
}
|
||
|
||
if(isset($_SESSION['select-columns'][$tableName])) {
|
||
$_SESSION['select-columns'][$tableName][] = "id";
|
||
$query->select($_SESSION['select-columns'][$tableName]);
|
||
}
|
||
|
||
if(getisset("group")) {
|
||
$groupColumnToQuery = $this->groupColumnToQuery($request, $query);
|
||
$query = $groupColumnToQuery['query'];
|
||
}
|
||
|
||
|
||
|
||
$query = $query->get();
|
||
|
||
$widthColumn = false;
|
||
if(getisset("with-column")) {
|
||
$widthColumn = true;
|
||
}
|
||
|
||
$result = [];
|
||
|
||
$except = [
|
||
//'created_at',
|
||
//'updated_at'
|
||
];
|
||
if($query->count()>0) {
|
||
if(getisset("group")) {
|
||
|
||
$groupColumns = j($request->group);
|
||
$key = $groupColumnToQuery['selectorName'];
|
||
// $items = $query->pluck($groupColumns[0]['selector'])->toArray();
|
||
$run = true;
|
||
if(getisset("skip")) {
|
||
if(!getesit("skip", "0")) {
|
||
$run = false;
|
||
}
|
||
}
|
||
|
||
if($run) {
|
||
|
||
$result['data'] = [];
|
||
$result['data'][] = [
|
||
'key' => null,
|
||
'count' => 0,
|
||
];
|
||
$added = [];
|
||
foreach($query AS $q) {
|
||
$keyValue = $q->$key;
|
||
|
||
if(strpos($key, "date") !== false) {
|
||
if($q->$key != "") {
|
||
$keyValue = date("Y/m/d", strtotime($q->$key));
|
||
if(!in_array($keyValue, $added)) {
|
||
$result['data'][] = [
|
||
'key' => $keyValue,
|
||
'count' => $q->total,
|
||
];
|
||
$added[] = $keyValue;
|
||
}
|
||
}
|
||
|
||
|
||
} else {
|
||
if(!in_array($keyValue, $added)) {
|
||
$result['data'][] = [
|
||
'key' => $keyValue,
|
||
'items' => null,
|
||
'count' => $q->total,
|
||
];
|
||
$added[] = $keyValue;
|
||
}
|
||
|
||
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
// $result['data']['totalCount'] = db($tableName)->count();
|
||
} else {
|
||
foreach($query AS $q) {
|
||
$data = [];
|
||
if($widthColumn) {
|
||
foreach($except AS $e) {
|
||
unset($q->$e);
|
||
}
|
||
$data = $q;
|
||
} else {
|
||
foreach($q AS $col => $value) {
|
||
if(!in_array($col, $except)) {
|
||
array_push($data, $value);
|
||
}
|
||
|
||
}
|
||
}
|
||
|
||
$result['data'][] = $data;
|
||
}
|
||
}
|
||
|
||
} else {
|
||
$result['data'] = [];
|
||
}
|
||
if(getesit("requireTotalCount", true)) {
|
||
$result['totalCount'] = db($tableName)->count();
|
||
}
|
||
|
||
|
||
//$result['data'] = $query;
|
||
|
||
return response()->json(
|
||
($result),
|
||
200,
|
||
[
|
||
'Content-Type' => 'application/json;charset=UTF-8',
|
||
'Charset' => 'utf-8'
|
||
],
|
||
JSON_UNESCAPED_UNICODE
|
||
);
|
||
|
||
}
|
||
|
||
private function groupColumnToQuery(Request $request, $query) {
|
||
$groupColumns = j($request->group);
|
||
$selector = $groupColumns[0]['selector'];
|
||
switch ($selector) {
|
||
case '{short_number}-{certificate_no}':
|
||
$selectorName = "certificate_no";
|
||
$query = $query
|
||
->select(
|
||
DB::raw("CONCAT(short_number, '-', certificate_no) AS certificate_no"),
|
||
DB::raw('count(*) as total'),
|
||
)
|
||
->groupBy("short_number", "certificate_no");
|
||
break;
|
||
case '{mat_group_1} + {mat_group_2}':
|
||
$selectorName = "mat_group_2";
|
||
$query = $query
|
||
->select(
|
||
DB::raw("CONCAT(mat_group_1, ' + ', mat_group_2) AS mat_group_2"),
|
||
DB::raw('count(*) as total'),
|
||
)
|
||
->groupBy("mat_group_1", "mat_group_2");
|
||
break;
|
||
|
||
default:
|
||
$selectorName = $selector;
|
||
$query = $query
|
||
->select(
|
||
$selector,
|
||
DB::raw('count(*) as total')
|
||
)
|
||
->groupBy($selector);
|
||
break;
|
||
}
|
||
if($selector == "{short_number}-{certificate_no}") {
|
||
|
||
} else {
|
||
|
||
}
|
||
|
||
return [
|
||
'query' => $query,
|
||
'selectorName' => $selectorName,
|
||
];
|
||
}
|
||
|
||
|
||
|
||
public function rowDetail(Request $request, string $tableName, string $columnName) {
|
||
$result = db($tableName);
|
||
|
||
if(!getesit("order", "")) {
|
||
$order = explode(":", get("order"));
|
||
$result = $result->orderBy($order[0], $order[1]);
|
||
}
|
||
|
||
if(is_array($request->value)) {
|
||
$result = $result->whereIn($columnName, $request->value)->get();
|
||
} else {
|
||
if(getisset("nolike")) {
|
||
$result = $result->where($columnName, $request->value)->first();
|
||
} else {
|
||
$result = $result->where($columnName, "LIKE", "%" . $request->value . "%")->first();
|
||
}
|
||
}
|
||
|
||
|
||
|
||
return response()->json(
|
||
($result),
|
||
200,
|
||
[
|
||
'Content-Type' => 'application/json;charset=UTF-8',
|
||
'Charset' => 'utf-8'
|
||
],
|
||
JSON_UNESCAPED_UNICODE
|
||
);
|
||
|
||
}
|
||
|
||
public function getDetail(Request $request, string $tableName, string $columnName, string $value) {
|
||
$result = db($tableName);
|
||
|
||
$result = $result->where($columnName, $value)->get();
|
||
|
||
return response()->json(
|
||
($result),
|
||
200,
|
||
[
|
||
'Content-Type' => 'application/json;charset=UTF-8',
|
||
'Charset' => 'utf-8'
|
||
],
|
||
JSON_UNESCAPED_UNICODE
|
||
);
|
||
|
||
}
|
||
|
||
|
||
public function create(Request $request, string $tableName) {
|
||
$post = $request->all();
|
||
unset($post['_token']);
|
||
if($tableName == "m_t_o_s") {
|
||
|
||
echo db($tableName)->updateOrInsert($post, [
|
||
'line' => $post['line'],
|
||
'component_code_id' => $post['component_code_id'],
|
||
]);
|
||
|
||
} elseif($tableName == "weld_logs") {
|
||
|
||
$exists = db($tableName)
|
||
->where("iso_number", $post['iso_number'])
|
||
->where("no_of_the_joint_as_per_as_built_survey", $post['no_of_the_joint_as_per_as_built_survey'])
|
||
->first();
|
||
|
||
dd($exists);
|
||
if(!$exists) {
|
||
echo db($tableName)->insert($post);
|
||
}
|
||
|
||
|
||
} else {
|
||
db($tableName)->insert($post);
|
||
}
|
||
|
||
return redirect()->back();
|
||
}
|
||
|
||
public function default(Request $request,string $type="",string $id="" )
|
||
{
|
||
$this->middleware('auth');
|
||
$p = $request -> all();
|
||
$contents = Contents::where("kid","main")
|
||
->orderBy("s","ASC") // s alanı sıralama alanıdır.
|
||
->get(); // tüm içeriklerdeki ana içerikler gelecek
|
||
$types = Types::orderBy("id","DESC")->get(); // tüm tipler
|
||
$alt = null;
|
||
$fields = null;
|
||
$content_fields = null;
|
||
$c = null;
|
||
$j = null;
|
||
$breadcrumb = null;
|
||
$ust = null;
|
||
$q = null;
|
||
$search_contents = null;
|
||
$seviye = null;
|
||
$users = null;
|
||
if(oturumisset("miktar")) {
|
||
$miktar = oturum("miktar");
|
||
} else {
|
||
$miktar = 10;
|
||
}
|
||
if(isset($p['m'])) {
|
||
$miktar = $p['m'];
|
||
oturum("miktar",$p['m']);
|
||
}
|
||
switch($type) {
|
||
case "users" :
|
||
|
||
break;
|
||
case "search" :
|
||
|
||
$q = $p['q'];
|
||
|
||
$searchFields = ['title','html','json','tkid','kid','type'];
|
||
$search_contents = Contents::where(function($query) use($request, $searchFields){
|
||
$searchWildcard = '%' . $request->q . '%';
|
||
foreach($searchFields as $field){
|
||
$query->orWhere($field, 'LIKE', $searchWildcard);
|
||
}
|
||
})
|
||
->get();
|
||
break;
|
||
//ilgili type ın ne olduğuna bakmak gerekli
|
||
case "types":
|
||
$c = Types::where("slug",$id)->first();
|
||
if(!$c) yonlendir("/admin");
|
||
if(isset($p['q'])) {
|
||
|
||
}
|
||
$q = get("q");
|
||
$searchFields = ['title','html','json','tkid','kid','breadcrumb'];
|
||
$alt = Contents::where("type",$c->title)
|
||
->where(function($query) use($request, $searchFields){
|
||
$searchWildcard = '%' . $request->q . '%';
|
||
foreach($searchFields as $field){
|
||
$query->orWhere($field, 'LIKE', $searchWildcard);
|
||
}
|
||
})
|
||
|
||
->orderBy("id","DESC")
|
||
->simplePaginate($miktar);;
|
||
break;
|
||
case "contents":
|
||
//content alanında çalışacak şeyler öncelikle ilgili itemin içeriği ve onun alt içerikleri
|
||
if($id=="") $view = "index";
|
||
else {
|
||
$c = Contents::where("slug",$id)->orWhere("id",$id)->first();
|
||
if($c->kid!="") {
|
||
$breadcrumb = Contents::getBreadcrumbs($c->kid);
|
||
$tree = Contents::getTree($id);
|
||
$breadcrumb2 = Contents::getBreadcrumbs($id,"{title} / ");
|
||
}else {
|
||
$breadcrumb = "";
|
||
$tree = "";
|
||
$breadcrumb2 = "";
|
||
}
|
||
|
||
$ust = Contents::where("slug",$c->kid)->first();
|
||
$j = @json_decode($c->json,true);
|
||
$alt = Contents::where("kid",$id)->orWhere("kid",$c->slug)->orderBy("s","ASC")->simplePaginate($miktar);
|
||
if($c->type!="") {
|
||
$content_type = Types::where("title",$c->type)->first(); // content type
|
||
$content_type = @explode(",",$content_type->fields);
|
||
}
|
||
if($c->tkid=="") {
|
||
DB::table("contents")
|
||
->where('id', $id)
|
||
->update([
|
||
'tkid' => json_encode($tree),
|
||
'breadcrumb' => $breadcrumb2
|
||
]);
|
||
|
||
}
|
||
if($c->type!="") {
|
||
$fields = Fields::get();
|
||
$fields = json_decode($fields,true);
|
||
$fields2 = array();
|
||
|
||
//burada ilgili içerik tipine ait alanların değerleri ve tip sistemini alıyoruz. Bunu dinamik form sisteminde kullanacağız
|
||
foreach(@$fields AS $r) {
|
||
if(in_array($r['title'],$content_type)) {
|
||
$fields2[$r['title']] = array(
|
||
"values" => explode(",",$r['values']),
|
||
"type" => $r['input_type']
|
||
);
|
||
}
|
||
|
||
}
|
||
$fields = $fields2;
|
||
if(isset($ct->fields)) {
|
||
$content_fields = explode(",",$ct->fields); // içerik alanları
|
||
}
|
||
}
|
||
} // if
|
||
|
||
|
||
|
||
|
||
break;
|
||
|
||
//bir içerik tipine ait olan alanların input type larının tutulduğu bir tablo bu sistem types tablosuna girilen fieldsları otomatik oluşturuyor.
|
||
case "fields" :
|
||
//input_type alanı boş olanları silelim
|
||
Fields::where('input_type', '=', '')
|
||
->orWhereNull('input_type')
|
||
->delete();
|
||
|
||
//tekrar oluşturalım tüm alanları
|
||
foreach($types AS $t) {
|
||
$fields = explode(",",$t->fields);
|
||
foreach($fields AS $r) {
|
||
$r = trim($r);
|
||
$c = Fields::where("title",$r)->first();
|
||
|
||
if($r!="") {
|
||
if($c == "") {
|
||
$row = new Fields();
|
||
$row->title = $r;
|
||
$row->type = $t->title;
|
||
$row->save();
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
$fields = Fields::get();
|
||
break;
|
||
default:
|
||
$alt = null;
|
||
$c = null;
|
||
break;
|
||
|
||
}
|
||
|
||
//eğer anasayfa geldi ise index gelmedi ise default
|
||
if($id=="" || $id=="index") {
|
||
$view = "index";
|
||
} else {
|
||
$view = "default";
|
||
}
|
||
|
||
//tüm değişkenleri bir dizi olarak aktarıyoruz gönderdiklerimiz mutlaka tanımlanmış olmalı ondan dolayı bazılarında null tanımını verdim yukarıda
|
||
$var = [
|
||
'q' => $q,
|
||
'miktar' => $miktar,
|
||
'type' => $type,
|
||
'users' => $users,
|
||
'seviye' => $seviye,
|
||
'breadcrumb' => $breadcrumb,
|
||
'search_contents' => $search_contents,
|
||
'content_fields' => $content_fields,
|
||
'fields' => $fields,
|
||
'alt' => $alt,
|
||
'id' => $id,
|
||
'c' => $c,
|
||
'ust' => $ust,
|
||
'j' => $j,
|
||
'contents' => $contents,
|
||
"types" => $types
|
||
];
|
||
//try catch hayat kurtarır. Adminde ilgili tipdeki blade lere yönlendiriir yoksa default veya indexe yönlendirir.
|
||
$permissions = userPermissions(); //explode(",",Auth::user()->permissions);
|
||
$permissions2 = array();
|
||
foreach($permissions AS $p) {
|
||
array_push($permissions2,str_slug($p));
|
||
}
|
||
$permissions = $permissions2;
|
||
|
||
if($type=="types") {
|
||
$alan = $id;
|
||
} else {
|
||
$alan = $type;
|
||
}
|
||
|
||
|
||
if($alan=="" && $id!="") {
|
||
|
||
return view('admin/'.$view, $var);
|
||
} else {
|
||
try {
|
||
//echo "$view $type $alan";
|
||
if(($view=="index") && $type=="") {
|
||
|
||
return view('admin/'.$view, $var);
|
||
} else {
|
||
|
||
if(in_array("all-privileges",$permissions)) { // Tüm yetkiler
|
||
return view("admin/$type",$var);
|
||
} else {
|
||
if($id != "devextreme")
|
||
{
|
||
return view("admin/$type",$var);
|
||
}
|
||
else
|
||
{
|
||
if(isAuth($id,"read")) {
|
||
|
||
return view("admin/$type",$var);
|
||
|
||
|
||
} else {
|
||
return view("admin/yetki-yok",$var);
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
|
||
}
|
||
|
||
} catch (\Exception $e) {
|
||
|
||
return view('admin/'.$view, $var);
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
|
||
/**
|
||
* User Guide functionality for module documentation
|
||
*/
|
||
public function userGuide($module = null)
|
||
{
|
||
// Tüm logic view içinde yapılıyor
|
||
return view('admin.user-guide');
|
||
}
|
||
|
||
/**
|
||
* Clone row functionality - includes table-specific logic
|
||
*/
|
||
public function cloneRow(Request $request, string $tableName)
|
||
{
|
||
$u = u();
|
||
if(!isset($u->level)) {
|
||
echo("permission error");
|
||
exit();
|
||
}
|
||
|
||
$data = j(post("data"));
|
||
$originalId = $data['id']; // Orijinal kaydın ID'sini saklayalım
|
||
unset($data['id']);
|
||
|
||
// Table-specific clone logic
|
||
$path = "app/Http/Controllers/CloneTrigger/{$tableName}.php";
|
||
if(file_exists($path)) {
|
||
$table = $tableName; // CloneTrigger dosyaları için $table değişkenini tanımla
|
||
include($path);
|
||
}
|
||
|
||
$data['created_at'] = Carbon::now();
|
||
|
||
if(isset($data['no_of_the_joint_as_per_as_built_survey'])) {
|
||
$data['no_of_the_joint_as_per_as_built_survey'] = "clone-" . $data['no_of_the_joint_as_per_as_built_survey'];
|
||
}
|
||
|
||
try {
|
||
// Kaydı ekleyelim ve yeni ID'yi alalım
|
||
$newId = db($tableName)->insertGetId($data);
|
||
|
||
if($tableName == "weld_logs") {
|
||
/*
|
||
view('cron.spool-status-changer', [
|
||
'spool_number' => $data['spool_number'],
|
||
'iso_number' => $data['iso_number'],
|
||
])->render();
|
||
*/
|
||
}
|
||
|
||
if($newId) {
|
||
// Klonlanan her alan için ColumnComment kaydı oluşturalım
|
||
foreach($data as $column => $value) {
|
||
// Bazı sütunları atlayalım
|
||
if(in_array($column, ['created_at', 'updated_at', 'deleted_at'])) {
|
||
continue;
|
||
}
|
||
|
||
// Null olmayan ve boş string olmayan değerler için kayıt oluştur
|
||
if($value !== null && $value !== '') {
|
||
ColumnComment::create([
|
||
'table_name' => $tableName,
|
||
'record_id' => $newId,
|
||
'column_name' => $column,
|
||
'comment' => "Cloned from record #$originalId",
|
||
'column_value' => $value,
|
||
'user_id' => Auth::id(),
|
||
'ip_address' => request()->ip()
|
||
]);
|
||
}
|
||
}
|
||
|
||
// Save trigger'larını çalıştırmak için gerekli değişkenleri oluştur
|
||
$beforeData = db($tableName)->where("id", $newId)->first();
|
||
$request = new \Illuminate\Http\Request();
|
||
$request['key'] = ['id' => $newId];
|
||
$request['values'] = $data;
|
||
$request['new_record'] = true;
|
||
|
||
// SaveTrigger'ı asenkron olarak çalıştır
|
||
$job = ExecuteSaveTriggerJob::dispatch(
|
||
$tableName,
|
||
$request->all(),
|
||
$request['key'],
|
||
$request['values'],
|
||
$beforeData,
|
||
"clone"
|
||
);
|
||
}
|
||
} catch (\Throwable $th) {
|
||
dump($th);
|
||
Log::error("$tableName Clone row error:" . $th->getMessage());
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Get unique column values for headerFilter
|
||
* Returns all distinct values from a specific column
|
||
*/
|
||
public function getUniqueColumnValues(Request $request, string $tableName, string $columnName) {
|
||
try {
|
||
// Get unique values from column
|
||
$uniqueValues = DB::table($tableName)
|
||
->select($columnName)
|
||
->distinct()
|
||
->whereNotNull($columnName)
|
||
->where($columnName, '!=', '')
|
||
->orderBy($columnName)
|
||
->pluck($columnName)
|
||
->toArray();
|
||
|
||
// Check if column has empty values
|
||
$hasEmpty = DB::table($tableName)
|
||
->where(function($query) use ($columnName) {
|
||
$query->whereNull($columnName)
|
||
->orWhere($columnName, '=', '');
|
||
})
|
||
->exists();
|
||
|
||
// Build result array
|
||
$result = array_map(function($value) {
|
||
return [
|
||
'text' => $value,
|
||
'value' => $value
|
||
];
|
||
}, $uniqueValues);
|
||
|
||
// Add empty option if exists
|
||
if ($hasEmpty) {
|
||
array_unshift($result, [
|
||
'text' => '(Boş)',
|
||
'value' => null
|
||
]);
|
||
}
|
||
|
||
return response()->json($result);
|
||
|
||
} catch (\Exception $e) {
|
||
Log::error("Get unique column values error: " . $e->getMessage());
|
||
return response()->json(['error' => $e->getMessage()], 500);
|
||
}
|
||
}
|
||
}
|