Files
citrus-cms/app/Http/Controllers/SaveTrigger/weld_logs_old.php
T
2026-04-28 21:14:25 +03:00

2435 lines
99 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
use App\Models\TestPackage;
use App\Models\PunchList;
use App\Models\TestPackBaseStatus;
use App\Models\PaintMatrix;
use App\Models\WeldLog;
use App\Models\PaintFollowUp;
use App\Models\NdeMatrix;
use App\Helpers\TransactionHelper;
// Start overall execution time
$overallStartTime = microtime(true);
// Database timeout and lock settings - ACTIVATED FOR LOCK PREVENTION
TransactionHelper::setDatabaseTimeouts(300, 600, 600);
// Memory limit increase
ini_set('memory_limit', '2G');
ini_set('max_execution_time', 600); // 10 minutes
$id = $request['key'];
Log::info("=== WELD LOG SAVE TRIGGER STARTED ===", [
'weld_log_id' => $id,
'timestamp' => now()->toDateTimeString(),
'memory_usage_start' => round(memory_get_usage(true) / 1024 / 1024, 2) . ' MB'
]);
$data = db($tableName)->where("id", $id)->first();
if(is_null($data)) {
$data = db($tableName)->where($id)->first();
}
$lineNumber = $data->line_number;
$testPackageNo = $data->test_package_no;
$logs_request_number_pattern = setting("logs_request_number_pattern");
// beforeData Job'dan geliyor, ek kontrol yapmaya gerek yok
// Sadece debug için log ekleyelim
Log::info("WeldLog SaveTrigger started", [
'weld_log_id' => $id,
'beforeData_available' => !is_null($beforeData) ? 'YES' : 'NO',
'action' => $action ?? 'unknown'
]);
// Yeni kayıt kontrolü - eğer beforeData null ise veya tüm alanlar aynıysa yeni kayıt
$isNewRecord = false;
if (is_null($beforeData)) {
$isNewRecord = true;
Log::info("WeldLog new record detected", [
'weld_log_id' => $id,
'reason' => 'beforeData_is_null'
]);
} else {
// Tüm alanları kontrol et - eğer hiç değişiklik yoksa yeni kayıt olabilir
$allFieldsMatch = true;
$dataArray = (array) $data; // stdClass'ı array'e çevir
foreach ($dataArray as $key => $value) {
if (isset($beforeData->$key) && $beforeData->$key != $value) {
$allFieldsMatch = false;
break;
}
}
if ($allFieldsMatch) {
$isNewRecord = true;
Log::info("WeldLog new record detected", [
'weld_log_id' => $id,
'reason' => 'all_fields_match'
]);
}
}
// Hangi alanların değiştiğini tespit et - İyileştirilmiş versiyon
$changedFields = [];
if (!is_null($beforeData)) {
$dataArray = (array) $data;
$beforeDataArray = (array) $beforeData;
foreach ($dataArray as $key => $value) {
$oldValue = $beforeDataArray[$key] ?? null;
if ($oldValue !== $value) {
$changedFields[] = $key;
}
}
} else {
// Eğer beforeData null ise, tüm alanlar değişmiş sayılır
$dataArray = (array) $data;
$changedFields = array_keys($dataArray);
}
Log::info("WeldLog changed fields detected", [
'weld_log_id' => $id,
'changed_fields' => $changedFields,
'is_new_record' => $isNewRecord,
'beforeData_available' => !is_null($beforeData) ? 'YES' : 'NO',
'action' => $action ?? 'unknown'
]);
// Alan gruplarını tanımla
$spoolRelatedFields = [
'spool_number',
'iso_number',
'type_of_joint',
'line_number', // Spool status changer için line_number da gerekli
'project', // Construction paint logs için
'design_area' // Construction paint logs için
];
$ndeRelatedFields = [
'type_of_welds',
'fluid_code',
'type_of_joint',
'line_number', // NDE Matrix oluşturma için
'design_area', // NDE Matrix için
'project' // NDE Matrix project alanı için
];
$testPackageRelatedFields = [
'test_package_no',
'iso_number',
'nps_1',
'nps_2',
'outside_diameter_1',
'outside_diameter_2',
'line_number', // Test package hesaplamaları için
'project', // Test package area bilgisi için
'design_area', // Test package unit bilgisi için
'piping_type', // Test package discipline bilgisi için
'circuit_number', // Test package için
'p_id', // Test package için
'type_of_test', // Test package test type için
'test_pressure', // Test package test pressure için
'quantity_of_iso', // Test package iso quantity için
'welding_date', // Test package progress hesaplamaları için
'rt_test_date', // Test package backlog hesaplamaları için
'ut_test_date', // Test package backlog hesaplamaları için
'mt_test_date', // Test package backlog hesaplamaları için
'pt_test_date', // Test package backlog hesaplamaları için
'vt_test_date', // Test package backlog hesaplamaları için
'pwht_test_date', // Test package backlog hesaplamaları için
'pmi_test_date', // Test package backlog hesaplamaları için
'ferrite_test_date', // Test package backlog hesaplamaları için
'no_of_the_joint_as_per_as_built_survey' // Golden joints hesaplaması için
];
$materialRelatedFields = [
'material_no_1',
'material_no_2',
'ru_material_group_1', // Material group güncellemesi sonrası
'ru_material_group_2' // Material group güncellemesi sonrası
];
$paintRelatedFields = [
'line_number',
'fluid_code',
'spool_number',
'no_of_the_joint_as_per_as_built_survey',
'project', // Paint follow up için
'design_area', // Paint follow up için
'iso_number', // Paint follow up için
'type_of_joint', // Paint follow up SHOP/FIELD ayrımı için
'weld_map_no' // Construction paint logs için
];
$handoverRelatedFields = [
'line_number',
'project',
'design_area',
'piping_type'
];
// Line Lists güncellemesi için ek alanlar
$lineListsRelatedFields = [
'line_number', // Ana trigger alanı
'design_area', // Line lists'ten weld_logs'a aktarım için
'fluid_code', // Line lists'ten weld_logs'a aktarım için
'type_of_welds' // Line lists'ten weld_logs'a aktarım için
];
// Request date işlemleri için ek alanlar
$requestDateRelatedFields = [
'iso_number', // Request number oluşturma için
'no_of_the_joint_as_per_as_built_survey', // Request number oluşturma için
'rt_request_date', 'rt_request_no', 'test_laboratory_rt', // RT test için
'ut_request_date', 'ut_request_no', 'test_laboratory_ut', // UT test için
'mt_request_date', 'mt_request_no', 'test_laboratory_mt', // MT test için
'pt_request_date', 'pt_request_no', 'test_laboratory_pt', // PT test için
'vt_request_date', 'vt_request_no', 'test_laboratory_vt', // VT test için
'pwht_request_date', 'pwht_request_no', 'test_laboratory_pwht', // PWHT test için
'ferrite_request_date', 'ferrite_request_no', 'test_laboratory_ferrite', // Ferrite test için
'pmi_request_date', 'pmi_request_no', 'test_laboratory_pmi' // PMI test için
];
// Repair logs güncellemesi için ek alanlar
$repairLogsRelatedFields = [
'iso_number', // Repair logs güncellemesi için
'no_of_the_joint_as_per_as_built_survey', // Repair logs güncellemesi için
'welding_date', // Repair logs repair_date güncellemesi için
'vt_result',
'rt_result',
'ut_result',
'pt_result',
'mt_result',
'pmi_result',
'ht_result',
'ferrite_result',
];
// NDE project name güncellemesi için ek alanlar
$ndeProjectRelatedFields = [
'line_number', // NDE Matrix project güncellemesi için
'project' // NDE Matrix project güncellemesi için
];
// Hangi trigger'ların çalışması gerektiğini belirle
$shouldRunSpoolStatusChanger = true; //$isNewRecord || !empty(array_intersect($changedFields, $spoolRelatedFields));
$shouldRunLineListsUpdate = $isNewRecord || true; //!empty(array_intersect($changedFields, $lineListsRelatedFields)); // Line lists ile ilgili alanlar değiştiğinde
$shouldRunNdeMatrixUpdate = $isNewRecord || true; //!empty(array_intersect($changedFields, $ndeRelatedFields));
$shouldRunTestPackageUpdate = $isNewRecord || !empty(array_intersect($changedFields, $testPackageRelatedFields));
$shouldRunMaterialGroupUpdate = $isNewRecord || true; //!empty(array_intersect($changedFields, $materialRelatedFields));
$shouldRunPaintFollowUpUpdate = $isNewRecord || !empty(array_intersect($changedFields, $paintRelatedFields));
$shouldRunHandoverUpdate = $isNewRecord || !empty(array_intersect($changedFields, $handoverRelatedFields));
$shouldRunRequestDateUpdate = $isNewRecord || !empty(array_intersect($changedFields, $requestDateRelatedFields));
$shouldRunRepairLogsUpdate = $isNewRecord || !empty(array_intersect($changedFields, $repairLogsRelatedFields));
$shouldRunNdeProjectUpdate = $isNewRecord || !empty(array_intersect($changedFields, $ndeProjectRelatedFields));
Log::info("WeldLog trigger decisions", [
'shouldRunSpoolStatusChanger' => $shouldRunSpoolStatusChanger,
'shouldRunLineListsUpdate' => $shouldRunLineListsUpdate,
'shouldRunNdeMatrixUpdate' => $shouldRunNdeMatrixUpdate,
'shouldRunTestPackageUpdate' => $shouldRunTestPackageUpdate,
'shouldRunMaterialGroupUpdate' => $shouldRunMaterialGroupUpdate,
'shouldRunPaintFollowUpUpdate' => $shouldRunPaintFollowUpUpdate,
'shouldRunHandoverUpdate' => $shouldRunHandoverUpdate,
'shouldRunRequestDateUpdate' => $shouldRunRequestDateUpdate,
'shouldRunRepairLogsUpdate' => $shouldRunRepairLogsUpdate,
'shouldRunNdeProjectUpdate' => $shouldRunNdeProjectUpdate,
'changed_fields' => $changedFields,
'is_new_record' => $isNewRecord,
'note' => 'LineListsUpdate now runs only when line-related fields change'
]);
// Spool Status Changer tetikleme kontrolü
if ($shouldRunSpoolStatusChanger) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [1/12] Spool Status Changer - STARTED", [
'weld_log_id' => $id,
'process' => 'Spool Status Changer'
]);
$triggerSpoolStatusChanger = false;
$spoolStatusChangerParams = [];
// spool_number değişikliği kontrolü
if (isset($data->spool_number)) {
if(isset($data->iso_number)) {
$triggerSpoolStatusChanger = true;
$spoolStatusChangerParams['spool_number'] = $data->spool_number;
$spoolStatusChangerParams['iso_number'] = $data->iso_number;
//dump("Spool number changed from '{$beforeData->spool_number}' to '{$data->spool_number}' - triggering spool status changer");
}
}
// type_of_joint değişikliği kontrolü - spool_status'ü 'Waiting' yap
if (isset($data->type_of_joint) && isset($beforeData->type_of_joint) &&
$data->type_of_joint !== $beforeData->type_of_joint) {
// Aynı spool_number ve iso_number'a sahip kayıtların spool_status'ünü 'Waiting' yap
if (isset($data->spool_number) && isset($data->iso_number)) {
$updateResult = db("weld_logs")
->where("id", $data->id)
->update(['spool_status' => 'Waiting']);
Log::info("Spool status updated to 'Waiting' due to type_of_joint change", [
'spool_number' => $data->spool_number,
'iso_number' => $data->iso_number,
'old_type_of_joint' => $beforeData->type_of_joint,
'new_type_of_joint' => $data->type_of_joint,
'updated_records' => $updateResult
]);
}
}
// Spool Status Changer'ı tetikle
if ($triggerSpoolStatusChanger) {
try {
// Yeni değerler için spool status changer'ı çalıştır (iso + spool birlikte tek view)
$spoolStatusChangerView = view('cron.spool-status-changer', $spoolStatusChangerParams)->render();
//dump("Spool Status Changer triggered successfully with params: " . json_encode($spoolStatusChangerParams));
// Eski değerler için de tetikle (eğer değişiklik varsa)
$oldParams = [];
if (isset($beforeData->spool_number) && isset($data->spool_number) && $beforeData->spool_number !== $data->spool_number) {
$oldParams['spool_number'] = $beforeData->spool_number;
}
if (isset($beforeData->iso_number) && isset($data->iso_number) && $beforeData->iso_number !== $data->iso_number) {
$oldParams['iso_number'] = $beforeData->iso_number;
}
// Eski değerler için tek view render
if (!empty($oldParams)) {
$oldSpoolStatusChangerView = view('cron.spool-status-changer', $oldParams)->render();
//dump("Spool Status Changer triggered for old values: " . json_encode($oldParams));
}
} catch (\Throwable $th) {
//dump("Error triggering Spool Status Changer: " . $th->getMessage());
Log::error("Spool Status Changer trigger error: " . $th->getMessage());
}
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [1/12] Spool Status Changer - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Spool Status Changer',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3)
]);
}
// Line Lists güncellemesi
if ($shouldRunLineListsUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [2/12] Line Lists Update - STARTED", [
'weld_log_id' => $id,
'process' => 'Line Lists Update'
]);
try {
// Line lists updated_at trigger for cron
db("line_lists")
->where(['line_no'=> $data->line_number])
->where(['unit'=> $data->design_area])
->update(["updated_at" => simdi()]);
// Line Lists'ten WeldLog'a veri aktarımını view render ile yap
$lineListsToWeldLogView = view('cron.line_lists-sync-from-linelists-to-weldlog', [
'line_number' => $data->line_number,
'design_area' => $data->design_area,
'commitSize' => 3, // Chunk size for transaction batching
'triggerMode' => true // SaveTrigger'dan çağrıldığını belirtmek için
])->render();
Log::info("Line Lists to WeldLog sync completed via view render", [
'view_render' => $lineListsToWeldLogView,
'line_number' => $data->line_number,
'design_area' => $data->design_area
]);
} catch (\Throwable $th) {
Log::error("Line Lists sync error: " . $th->getMessage(), [
'line_number' => $data->line_number,
'design_area' => $data->design_area
]);
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [2/12] Line Lists Update - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Line Lists Update',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3)
]);
}
// NDE Matrix güncellemesi
if ($shouldRunNdeMatrixUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [3/12] NDE Matrix Update - STARTED", [
'weld_log_id' => $id,
'process' => 'NDE Matrix Update'
]);
try {
// Line Lists'ten NDE Matrix'e veri aktarımını view render ile yap
$ndeMatrixView = view('cron.line_lists-sync-from-linelists-nde-matrix', [
'line_number' => $data->line_number,
'design_area' => $data->design_area,
'commitSize' => 5, // Chunk size for transaction batching
'triggerMode' => true // SaveTrigger'dan çağrıldığını belirtmek için
])->render();
Log::info("Line Lists to NDE Matrix sync completed via view render", [
'line_number' => $data->line_number,
'design_area' => $data->design_area
]);
// Type of weld değişikliği için özel işlem
if (!is_null($beforeData) && $beforeData->type_of_welds !== $data->type_of_welds) {
TransactionHelper::retryTransaction(function () use ($data, $beforeData) {
// Eski tip için where koşulu
$oldTypeWhereData = [
'line' => $data->line_number,
'type_of_joint' => $beforeData->type_of_welds,
'fluid' => $data->fluid_code,
];
// Eski tipin başka WeldLog kayıtlarında hala kullanılıp kullanılmadığını kontrol et
$otherRecordsUsingOldType = db("weld_logs")
->where('line_number', $data->line_number)
->where('type_of_welds', $beforeData->type_of_welds)
->where('fluid_code', $data->fluid_code)
->where('id', '!=', $data->id)
->orderBy('id', 'ASC') // Deadlock prevention
->exists();
// Sadece eski tip başka yerde kullanılmıyorsa NDE Matrix'ten sil
if (!$otherRecordsUsingOldType) {
$deleteResult = db("nde_matrices")
->where($oldTypeWhereData)
->delete();
Log::info("NDE Matrix old type cleaned up - no other weld logs using it", [
'line' => $data->line_number,
'old_type_of_joint' => $beforeData->type_of_welds,
'new_type_of_joint' => $data->type_of_welds,
'fluid' => $data->fluid_code,
'delete_result' => $deleteResult
]);
} else {
Log::info("NDE Matrix old type preserved - still used by other weld logs", [
'line' => $data->line_number,
'old_type_of_joint' => $beforeData->type_of_welds,
'new_type_of_joint' => $data->type_of_welds,
'fluid' => $data->fluid_code
]);
}
}, 5); // 5 attempts with exponential backoff
}
} catch (\Throwable $th) {
Log::error("NDE Matrix sync error: " . $th->getMessage(), [
'line_number' => $data->line_number,
'design_area' => $data->design_area
]);
}
// NDE Matrix'ten WeldLog'a veri aktarımı
// fluid_code null kontrolü - line_lists'ten al
$currentFluidCode = $data->fluid_code ?? '';
if(empty($currentFluidCode)) {
$lineListForFluid = db("line_lists")->where('line_no', $data->line_number)->first();
if($lineListForFluid) {
$currentFluidCode = $lineListForFluid->fluid_code ?? '';
}
}
Log::info("NDE Matrix to WeldLog sync started", [
'weld_log_id' => $id,
'line_number' => $data->line_number,
'type_of_welds' => $data->type_of_welds,
'fluid_code' => $currentFluidCode
]);
// fluid_code null ise işlemi atla
if(empty($currentFluidCode)) {
Log::info("NDE Matrix to WeldLog sync skipped - fluid_code is null", [
'weld_log_id' => $id,
'line_number' => $data->line_number
]);
} else {
// NDE Matrix'ten ilgili kayıtları al
$ndeMatrices = NdeMatrix::where("line", $data->line_number)
->where("type_of_joint", $data->type_of_welds)
->where("fluid", $currentFluidCode)
->get();
Log::debug("Data", ['line_number' => $data->line_number, 'type_of_welds' => $data->type_of_welds, 'fluid_code' => $currentFluidCode]);
Log::debug("NDE Matrix kayıtları çekildi", [
'matrix_count' => $ndeMatrices->count(),
'matrix_examples' => $ndeMatrices->take(2)->toArray()
]);
$ndeToWeldLogUpdateCount = 0;
// NDE Matrix işlemlerini chunk'lara böl ve TransactionHelper ile işle
Log::debug("NDE Matrix to WeldLog sync starting", [
'total_records' => $ndeMatrices->count()
]);
TransactionHelper::chunkTransaction(
$ndeMatrices,
function ($ndeMatrixChunk) use (&$ndeToWeldLogUpdateCount) {
foreach($ndeMatrixChunk as $ndeMatrix) {
$weldLogUpdateData = [
'vt_scope' => 100,
'rt_scope' => $ndeMatrix->rt,
'ut_scope' => $ndeMatrix->ut,
'mt_scope' => $ndeMatrix->mt,
'pt_scope' => $ndeMatrix->pt,
'pmi_scope' => $ndeMatrix->pmi,
'ht_scope' => $ndeMatrix->ht,
'pwht' => $ndeMatrix->pwht_field,
'ferrite_scope' => $ndeMatrix->fn,
'ndt_percent' => $ndeMatrix->ndt,
'operating_temperature_s' => $ndeMatrix->operation_temp,
'operating_pressure_mpa' => $ndeMatrix->operations_pressure_kg,
'fluid_group' => $ndeMatrix->piping_group,
'main_material' => $ndeMatrix->material,
'updated_at' => simdi()
];
$result = db("weld_logs")
->where("line_number", $ndeMatrix->line)
->where("type_of_welds", $ndeMatrix->type_of_joint)
->orderBy('id', 'ASC') // Deadlock prevention
->update($weldLogUpdateData);
$ndeToWeldLogUpdateCount += $result;
}
return $ndeMatrixChunk->count();
},
10, // Chunk size increased from 3 to 10 for better performance
10000 // 10ms delay (reduced from 150ms) - sufficient for deadlock prevention
);
Log::info("NDE Matrix to WeldLog sync completed", [
'toplam_guncellenen_kayit' => $ndeToWeldLogUpdateCount
]);
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [3/12] NDE Matrix Update - COMPLETED", [
'weld_log_id' => $id,
'process' => 'NDE Matrix Update',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3)
]);
}
// Request date işlemleri
if ($shouldRunRequestDateUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [4/12] Request Date Operations - STARTED", [
'weld_log_id' => $id,
'process' => 'Request Date Operations',
'iso_number' => $data->iso_number,
'joint_no' => $data->no_of_the_joint_as_per_as_built_survey
]);
$logTestTypes = log_test_types();
Log::info("Available test types for request date processing", [
'test_types' => array_keys($logTestTypes)
]);
$testNames = array_keys($logTestTypes);
$testTableNames = array_values($logTestTypes);
foreach($testNames AS $testName) {
$requestDate = $testName . "_request_date";
$run = false;
$testTableName = $logTestTypes[$testName];
Log::info("Processing test type", [
'test_name' => $testName,
'request_date_field' => $requestDate,
'current_request_date' => $data->$requestDate ?? 'null',
'before_request_date' => $beforeData->$requestDate ?? 'null'
]);
if($data->$requestDate != "") {
$requestNo = $testName . "_request_no";
$laboratoryCompany = "test_laboratory_" . $testName;
Log::info("Request date is not empty, checking conditions", [
'test_name' => $testName,
'request_date' => $data->$requestDate,
'current_request_no' => $data->$requestNo ?? 'null',
'current_laboratory' => $data->$laboratoryCompany ?? 'null',
'before_laboratory' => $beforeData->$laboratoryCompany ?? 'null'
]);
if($data->$requestNo == "") {
// request no daha önce atanmadıysa
$run = true;
Log::info("Run condition met: Request number is empty", [
'test_name' => $testName,
'reason' => 'request_no_empty'
]);
}
if($data->$laboratoryCompany != $beforeData->$laboratoryCompany) {
// laboratuar değiştiğinde
$run = true;
Log::info("Run condition met: Laboratory changed", [
'test_name' => $testName,
'reason' => 'laboratory_changed',
'old_laboratory' => $beforeData->$laboratoryCompany ?? 'null',
'new_laboratory' => $data->$laboratoryCompany ?? 'null'
]);
}
$requestDateChange = false;
if($data->$requestDate != $beforeData->$requestDate) {
// request date değiştiğinde
$run = true;
Log::info("Run condition met: Request date changed", [
'test_name' => $testName,
'reason' => 'request_date_changed',
'old_date' => $beforeData->$requestDate ?? 'null',
'new_date' => $data->$requestDate
]);
//önce bu tarihe göre verilen no varsa
$isOldSignReqDate = db("weld_logs")
->where([
$requestDate => $data->$requestDate,
$laboratoryCompany => $data->$laboratoryCompany,
])
->where("id", "<>", $data->id)
->first();
if(!$isOldSignReqDate) {
$requestDateChange = true;
Log::info("Request date is unique, will generate new request number", [
'test_name' => $testName,
'request_date' => $data->$requestDate,
'laboratory' => $data->$laboratoryCompany ?? 'null'
]);
} else {
Log::info("Request date already exists, will reuse existing request number", [
'test_name' => $testName,
'request_date' => $data->$requestDate,
'laboratory' => $data->$laboratoryCompany ?? 'null',
'existing_record_id' => $isOldSignReqDate->id ?? 'null'
]);
}
}
if($run) {
Log::info("Starting request number generation process", [
'test_name' => $testName,
'request_date_changed' => $requestDateChange,
'current_request_no' => $data->$requestNo ?? 'null',
'laboratory' => $data->$laboratoryCompany ?? 'null'
]);
$thisRequestNumberPattern = $logs_request_number_pattern;
$companyCode = db("subcontractors")->where("company_name_en", $data->$laboratoryCompany)->first();
if(!is_null($companyCode)) {
$companyCode = $companyCode->company_code;
} else {
$companyCode = "";
}
Log::info("Company code resolved", [
'test_name' => $testName,
'laboratory_name' => $data->$laboratoryCompany ?? 'null',
'company_code' => $companyCode
]);
$thisRequestNumberPattern = str_replace("{company_code}", $companyCode, $thisRequestNumberPattern);
if($requestDateChange) { //eğer daha önceki tarihten farklıysa yeni no ata
$lastRequestNumber = get_counter($companyCode . $testName);
Log::info("Getting new counter for date change", [
'test_name' => $testName,
'counter_key' => $companyCode . $testName,
'new_counter' => $lastRequestNumber
]);
} else { //eğer date aynı ise daha önceki tarih ataması yapıldıysa onu al ya da yeni ata
$lastRequestNumber = get_counter($companyCode . $testName, "");
Log::info("Getting existing or new counter for same date", [
'test_name' => $testName,
'counter_key' => $companyCode . $testName,
'counter' => $lastRequestNumber
]);
}
$thisRequestNumberPattern = str_replace("{number}", $lastRequestNumber, $thisRequestNumberPattern);
$thisRequestNumberPattern = str_replace("{log_name}", strtoupper($testName), $thisRequestNumberPattern);
Log::info("Request number pattern generated", [
'test_name' => $testName,
'pattern' => $thisRequestNumberPattern,
'counter' => $lastRequestNumber
]);
//eğer bu firmaya bugün daha önce bir request no atandıysa o numaranın aynısını al
$todayDataThisCompanyThisTest = db("weld_logs")->where([
$requestDate => $data->$requestDate,
$laboratoryCompany => $data->$laboratoryCompany,
])->first();
if($todayDataThisCompanyThisTest) {
if($todayDataThisCompanyThisTest->$requestNo !="") {
$thisRequestNumberPattern = $todayDataThisCompanyThisTest->$requestNo;
Log::info("Reusing existing request number for same date/company", [
'test_name' => $testName,
'existing_request_no' => $thisRequestNumberPattern,
'existing_record_id' => $todayDataThisCompanyThisTest->id
]);
}
}
$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,
];
$updateData = [
$requestNo => $thisRequestNumberPattern,
"updated_at" => simdi()
];
Log::info("Updating weld_logs with request number", [
'test_name' => $testName,
'where_data' => $whereData,
'update_data' => $updateData,
'final_request_number' => $thisRequestNumberPattern
]);
$weldLogUpdateResult = db("weld_logs")
->where($whereData)
->update($updateData);
Log::info("Weld_logs update completed", [
'test_name' => $testName,
'affected_rows' => $weldLogUpdateResult,
'request_number' => $thisRequestNumberPattern
]);
$weldLogData = db("weld_logs")->where($whereData)->first();
$testTableUpdateData = [];
$testTableColumns = table_columns($testTableName);
foreach($weldLogData AS $weldLogColumn => $weldLogValue)
{
if(in_array($weldLogColumn, $testTableColumns))
{
$testTableUpdateData[$weldLogColumn] = $weldLogValue;
}
}
unset($testTableUpdateData['id']);
Log::info("Updating test table with weld log data", [
'test_name' => $testName,
'test_table' => $testTableName,
'where_data' => $whereData,
'update_fields_count' => count($testTableUpdateData)
]);
$testTableUpdateResult = db($testTableName)
->updateOrInsert($whereData, $testTableUpdateData);
Log::info("Test table update completed", [
'test_name' => $testName,
'test_table' => $testTableName,
'operation_result' => $testTableUpdateResult ? 'success' : 'failed'
]);
} else {
Log::info("Request number generation skipped", [
'test_name' => $testName,
'reason' => 'run_condition_false',
'current_request_date' => $data->$requestDate ?? 'null',
'current_request_no' => $data->$requestNo ?? 'null'
]);
}
} else {
Log::info("Test processing skipped", [
'test_name' => $testName,
'reason' => 'request_date_empty',
'request_date_field' => $requestDate
]);
}
Log::info("Test type processing completed", [
'test_name' => $testName,
'run_executed' => $run
]);
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [4/12] Request Date Operations - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Request Date Operations',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3),
'processed_test_types' => count($testNames)
]);
}
// Repair logs güncelleme
if ($shouldRunRepairLogsUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [5/12] Repair Logs Update - STARTED", [
'weld_log_id' => $id,
'process' => 'Repair Logs Update'
]);
// Check if any test result contains "Repair / Ремонт" or "Cut / Резать"
$testResultFields = [
'vt_result',
'rt_result',
'ut_result',
'pt_result',
'mt_result',
'pmi_result',
'ht_result',
'ferrite_result'
];
$hasRepairOrCut = false;
$allFieldsEmpty = true;
$rtAndUtEmpty = false;
// Check if RT or UT results are empty
if(empty($data->rt_result) && empty($data->ut_result)) {
$rtAndUtEmpty = true;
}
foreach($testResultFields as $field) {
if(isset($data->$field) && !empty($data->$field)) {
$allFieldsEmpty = false;
if(in_array($data->$field, ['Repair / Ремонт', 'Cut / Резать'])) {
$hasRepairOrCut = true;
break;
}
}
}
// Determine repair status based on test results
if($allFieldsEmpty || $rtAndUtEmpty) {
$repairStatus = "Not Done";
} elseif(!$hasRepairOrCut) {
$repairStatus = "Done";
} else {
$repairStatus = "Repair";
}
db("repair_logs")
->where([
'iso_number' => $data->iso_number,
'new_joint_no' => $data->no_of_the_joint_as_per_as_built_survey,
])
->update([
'repair_date' => $data->welding_date,
'repair_status' => $repairStatus,
]);
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [5/12] Repair Logs Update - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Repair Logs Update',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3)
]);
}
// NDE project name güncelleme
if ($shouldRunNdeProjectUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [6/12] NDE Project Update - STARTED", [
'weld_log_id' => $id,
'process' => 'NDE Project Update'
]);
$ndeMatrices = DB::table('nde_matrices')
->join('weld_logs', function($join) {
$join->on('nde_matrices.line', '=', 'weld_logs.line_number')
->on('nde_matrices.design_area', '=', 'weld_logs.design_area');
})
->whereNull('nde_matrices.project'); // project sütunu boş olanları bul
$ndeMatrices = $ndeMatrices->where("weld_logs.id", $id);
$ndeMatrices = $ndeMatrices
->update([
'nde_matrices.project' => DB::raw('weld_logs.project') // weld_logs tablosundaki project değeri ile güncelle
]);
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [6/12] NDE Project Update - COMPLETED", [
'weld_log_id' => $id,
'process' => 'NDE Project Update',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3)
]);
}
// Paint Follow Up işlemleri
if ($shouldRunPaintFollowUpUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [8/12] Paint Follow Up Operations - STARTED", [
'weld_log_id' => $id,
'process' => 'Paint Follow Up Operations'
]);
$weldLogs = WeldLog::
where("no_of_the_joint_as_per_as_built_survey", "not like", "%clone%");
$weldLogs = $weldLogs->where("id", $id);
$weldLogs = $weldLogs
->get();
$paintMatrices = PaintMatrix:://groupBy("line", "fluid_code")->
get();
$spoolDatas = [];
$jointDatas = [];
$datas = [];
$deletedJoints= [];
foreach($weldLogs AS $weldLog) {
$spoolDatas[$weldLog->line_number][$weldLog->fluid_code][] = [
'spool_no_joint_no' => $weldLog->spool_number,
'fluid_code' => $weldLog->fluid_code,
'iso_number' => $weldLog->iso_number,
'line' => $weldLog->line_number,
];
$jointNo = $weldLog->no_of_the_joint_as_per_as_built_survey;
$jointType = "Normal";
if(strpos($jointNo, "R") !== false) {
$jointType = "Repair";
$otherJointNo = deleteAfterR($jointNo);
$deletedJoints[] = $otherJointNo;
}
$jointDatas[$weldLog->line_number][$weldLog->fluid_code][] = [
'spool_no_joint_no' => $weldLog->no_of_the_joint_as_per_as_built_survey,
'fluid_code' => $weldLog->fluid_code,
'iso_number' => $weldLog->iso_number,
'line' => $weldLog->line_number,
];
}
foreach($deletedJoints AS $deleteJoint) {
removeItemBySpoolNoJointNo($jointDatas, $deleteJoint);
}
foreach($paintMatrices AS $paintMatrix) {
$thisData = [
'project' => $paintMatrix->project,
'description' => $paintMatrix->description,
'area' => $paintMatrix->area,
'cycle' => $paintMatrix->paint_cycle,
'primer_coat_name_1' => $paintMatrix->primer_coat,
'ral_code_1' => $paintMatrix->ral_code_1,
'colour_1' => $paintMatrix->colour_1,
'colour_2' => $paintMatrix->colour_2,
'colour_3' => $paintMatrix->colour_3,
'brend_name_1' => $paintMatrix->brend_name_1,
'brend_name_2' => $paintMatrix->brend_name_2,
'brend_name_3' => $paintMatrix->brend_name_3,
'thickness_1' => $paintMatrix->thickness_1,
'intermediate_coat_name_2' => $paintMatrix->intermediate_coat,
'ral_code_2' => $paintMatrix->ral_code_2,
'thickness_2' => $paintMatrix->thickness_2,
'final_coat_name_3' => $paintMatrix->final_coat,
'ral_code_3' => $paintMatrix->ral_code_3,
'thickness_3' => $paintMatrix->thickness_3,
];
if(isset($spoolDatas[$paintMatrix->line][$paintMatrix->fluid_code])) {
foreach($spoolDatas[$paintMatrix->line][$paintMatrix->fluid_code] AS $spoolData) {
$thisData['location'] = "SHOP";
$mergedData = array_merge($spoolData, $thisData);
$datas[$paintMatrix->line][$paintMatrix->fluid_code][] = $mergedData;
}
}
if(isset($jointDatas[$paintMatrix->line][$paintMatrix->fluid_code])) {
foreach($jointDatas[$paintMatrix->line][$paintMatrix->fluid_code] AS $jointData) {
$thisData['location'] = "FIELD";
$mergedData = array_merge($jointData, $thisData);
$datas[$paintMatrix->line][$paintMatrix->fluid_code][] = $mergedData;
}
}
}
$paintFollowUpCount = 0;
foreach($datas AS $line => $data) {
foreach($data AS $fluid_code => $updateDatas) {
foreach($updateDatas AS $updateData) {
$whereData = [
'fluid_code' => $fluid_code,
'spool_no_joint_no' => $updateData['spool_no_joint_no'],
'line' => $line,
];
PaintFollowUp::updateOrCreate($whereData, $updateData);
$paintFollowUpCount++;
}
}
}
//dump("$paintFollowUpCount Data has been sync WeldLog ==> Paint Follow Up [fluid_code + spool_no_joint_no + line] (update or create)");
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [8/12] Paint Follow Up Operations - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Paint Follow Up Operations',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3),
'records_processed' => $paintFollowUpCount
]);
}
// Construction Paint Logs Sync
if ($shouldRunPaintFollowUpUpdate) { // Construction Paint Logs bölümü de paint işlemleri ile ilgili
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [9/12] Construction Paint Logs Sync - STARTED", [
'weld_log_id' => $id,
'process' => 'Construction Paint Logs Sync'
]);
$constructionPaintLogUpdatedCount = 0;
$constructionPaintLogCreatedCount = 0;
try {
// Get weld log data for the current ID
$weldLog = db("weld_logs")->where("id", $id)->first();
if ($weldLog) {
// Skip processing if essential fields are missing
if (empty($weldLog->line_number)) {
return;
}
// Retrieve all weld logs with the same line number
$allWeldLogs = db("weld_logs")
->where("line_number", $weldLog->line_number)
->orderBy('id', 'ASC') // Deadlock prevention
->get();
// Get line list data for additional information
$lineList = db("line_lists")
->where('line_no', $weldLog->line_number)
->first();
// Construction Paint Logs işlemlerini chunk'lara böl ve TransactionHelper ile işle
TransactionHelper::chunkTransaction(
$allWeldLogs,
function ($weldLogChunk) use ($lineList, &$constructionPaintLogUpdatedCount, &$constructionPaintLogCreatedCount) {
foreach ($weldLogChunk as $currentWeldLog) {
// Get paint matrix data for paint system information
$paintMatrix = PaintMatrix::where('line', $currentWeldLog->line_number)
->where('fluid_code', $currentWeldLog->fluid_code)
->first();
// Base data for construction paint log
$baseConstructionPaintLogData = [
// Report Information
'construction_report_no' => $currentWeldLog->weld_map_no ?? '',
'test_package' => $currentWeldLog->test_package_no ?? '',
'rev' => $lineList ? $lineList->rev : '',
// Project Information
'engineering' => $lineList->engineering ?? '',
'area' => $currentWeldLog->project ?? '',
'unit' => $currentWeldLog->design_area ?? '',
// 'paint_subcontructer' => $currentWeldLog->ste_subcontractor ?? '',
// Line Details
'line' => $currentWeldLog->line_number,
'iso_drawings' => $currentWeldLog->iso_number ?? '',
'fluid_code' => $currentWeldLog->fluid_code ?? '',
'fluid_code_description' => $lineList->fluid_ru ?? '',
'isolation_info' => $lineList->external_finish_type ?? '',
];
// Add paint system data if available
if ($paintMatrix) {
$paintSystemData = [
'painting_system_type_1' => $paintMatrix->paint_cycle ?? '',
'painting_system_type_2' => $paintMatrix->paint_cycle ?? '',
'brend_name_1' => $paintMatrix->brend_name_1 ?? '',
'ral_1' => $paintMatrix->ral_code_1 ?? '',
'thickness_1' => $paintMatrix->thickness_1 ?? '',
'brend_name_2' => $paintMatrix->brend_name_2 ?? '',
'ral_2' => $paintMatrix->ral_code_2 ?? '',
'thickness_2' => $paintMatrix->thickness_2 ?? '',
'brend_name_3' => $paintMatrix->brend_name_3 ?? '',
'ral_3' => $paintMatrix->ral_code_3 ?? '',
'thickness_3' => $paintMatrix->thickness_3 ?? '',
];
$baseConstructionPaintLogData = array_merge($baseConstructionPaintLogData, $paintSystemData);
}
// Add timestamp
$baseConstructionPaintLogData['updated_at'] = now();
// Process only the specific spool
$constructionPaintLogData = $baseConstructionPaintLogData;
// Add spool-specific data
$constructionPaintLogData['test_package'] = $currentWeldLog->test_package_no ?? '';
$constructionPaintLogData['spool'] = $currentWeldLog->spool_number ?? '';
$constructionPaintLogData['spool_status'] = $currentWeldLog->spool_status ?? 'Waiting';
// Generate unique report number for the spool
$constructionPaintLogData['report_no'] = '';
// Add dimensions
$constructionPaintLogData['dn_1'] = $currentWeldLog->nps_1 ?? '';
$constructionPaintLogData['dn_2'] = $currentWeldLog->nps_2 ?? '';
$constructionPaintLogData['dn_3'] = '';
// Define where condition to find or create the record
$whereCondition = [
'line' => $currentWeldLog->line_number,
'spool' => $currentWeldLog->spool_number
];
// Check if there is at least one 'S' type joint in this line
$hasShopJoint = db("weld_logs")
->where('line_number', $currentWeldLog->line_number)
->where('spool_number', $currentWeldLog->spool_number)
->where('type_of_joint', 'S')
->exists();
if ($hasShopJoint && !empty($currentWeldLog->spool_number)) {
// Check if record exists
$existingRecord = db("construction_paint_logs")
->where($whereCondition)
->first();
if ($existingRecord) {
// Update existing record
db("construction_paint_logs")
->where('id', $existingRecord->id)
->update($constructionPaintLogData);
$constructionPaintLogUpdatedCount++;
} else {
// Create new record
$constructionPaintLogData['created_at'] = now();
db("construction_paint_logs")->insert($constructionPaintLogData);
$constructionPaintLogCreatedCount++;
}
} else {
if (empty($currentWeldLog->spool_number)) {
//dump("Skipping construction paint log for spool - empty spool number");
} else {
//dump("Skipping construction paint log for line {$currentWeldLog->line_number} - no shop joints found");
}
}
}
return $weldLogChunk->count();
},
10, // Chunk size increased from 3 to 10 for better performance
10000 // 10ms delay (reduced from 150ms) - sufficient for deadlock prevention
);
}
} catch (\Throwable $th) {
Log::error("Construction Paint Logs sync error: " . $th->getMessage());
// Log detailed error information for debugging
Log::error("Error details: ", [
'weldLogId' => $id,
'exception' => get_class($th),
'file' => $th->getFile(),
'line' => $th->getLine(),
'trace' => $th->getTraceAsString()
]);
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [9/12] Construction Paint Logs Sync - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Construction Paint Logs Sync',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3),
'created' => $constructionPaintLogCreatedCount,
'updated' => $constructionPaintLogUpdatedCount
]);
}
?>
<?php
// İşlem süresi takibi
$endTime = microtime(true);
$executionTime = $endTime - ($_SERVER['REQUEST_TIME_FLOAT'] ?? $endTime);
//dump("Total execution time: " . round($executionTime, 2) . " seconds");
// Memory kullanımı
$memoryUsage = memory_get_peak_usage(true) / 1024 / 1024;
//dump("Peak memory usage: " . round($memoryUsage, 2) . " MB");
// İşlem tamamlandı log'u
$overallEndTime = microtime(true);
$overallDuration = round(($overallEndTime - $overallStartTime) * 1000, 2);
Log::info("=== WELD LOG SAVE TRIGGER COMPLETED ===", [
'weld_log_id' => $id,
'timestamp' => now()->toDateTimeString(),
'total_execution_time_ms' => $overallDuration,
'total_execution_time_sec' => round($overallDuration / 1000, 3),
'peak_memory_usage_mb' => round(memory_get_peak_usage(true) / 1024 / 1024, 2),
'final_memory_usage_mb' => round(memory_get_usage(true) / 1024 / 1024, 2)
]);
// Test pack base status changer
if ($shouldRunTestPackageUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [10/12] Test Pack Base Status Changer - STARTED", [
'weld_log_id' => $id,
'process' => 'Test Pack Base Status Changer'
]);
$testPackages = TestPackage::where("test_package_number", $testPackageNo)->get();
$testPackagesIso = TestPackBaseStatus::where("test_package_no", $testPackageNo)->get();
$weldLogs = db("weld_logs")
->where("line_number", $lineNumber)
->get();
$repairLogs = db("repair_logs")
->where("line_number", $lineNumber)
->get();
$testPackagesSummary = [];
$testPackagesIsoSummary = [];
$totalFields = [
'total_wdi',
'total_complated_wdi',
'welding_progress',
'total_shop_wdi',
'total_complated_shop_wdi',
'total_field_wdi',
'total_complated_field_wdi',
];
$repairLogsSummary = [];
$repairLogsSummary2 = [];
$repairLogsSummaryCompleted = [];
$repairLogsSummaryCompleted2 = [];
$repairLogsSummaryRemaining = [];
$repairLogsSummaryRemaining2 = [];
foreach($repairLogs AS $repairLog) {
if(!isset($repairLogsSummary[$repairLog->iso_number][$repairLog->test_package_no]))
$repairLogsSummary[$repairLog->iso_number][$repairLog->test_package_no] = 0;
if(!isset($repairLogsSummary2[$repairLog->test_package_no]))
$repairLogsSummary2[$repairLog->test_package_no] = 0;
if(!isset($repairLogsSummaryCompleted[$repairLog->iso_number][$repairLog->test_package_no]))
$repairLogsSummaryCompleted[$repairLog->iso_number][$repairLog->test_package_no] = 0;
if(!isset($repairLogsSummaryRemaining[$repairLog->iso_number][$repairLog->test_package_no]))
$repairLogsSummaryRemaining[$repairLog->iso_number][$repairLog->test_package_no] = 0;
if(!isset($repairLogsSummaryCompleted2[$repairLog->test_package_no]))
$repairLogsSummaryCompleted2[$repairLog->test_package_no] = 0;
if(!isset($repairLogsSummaryRemaining2[$repairLog->test_package_no]))
$repairLogsSummaryRemaining2[$repairLog->test_package_no] = 0;
if($repairLog->repair_status == "Not Done") {
$repairLogsSummary[$repairLog->iso_number][$repairLog->test_package_no]++;
$repairLogsSummary2[$repairLog->test_package_no]++;
}
if(!rejected_date($repairLog->repair_date))
{
$repairLogsSummaryCompleted[$repairLog->iso_number][$repairLog->test_package_no]++;
$repairLogsSummaryCompleted2[$repairLog->test_package_no]++;
} else {
$repairLogsSummaryRemaining[$repairLog->iso_number][$repairLog->test_package_no]++;
$repairLogsSummaryRemaining2[$repairLog->test_package_no]++;
}
}
foreach($weldLogs AS $weldLog) {
foreach($totalFields AS $field) {
if(!isset($testPackagesSummary[$weldLog->test_package_no][$field]))
$testPackagesSummary[$weldLog->test_package_no][$field] = 0;
if(!isset($testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no][$field]))
$testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no][$field] = 0;
}
$wdi = (float) $weldLog->nps_1;
$testPackagesSummary[$weldLog->test_package_no]['total_wdi'] += $wdi ;
$testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no]['total_wdi'] += $wdi;
if($weldLog->type_of_joint == "F") {
$testPackagesSummary[$weldLog->test_package_no]['total_field_wdi'] += $wdi;
$testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no]['total_field_wdi'] += $wdi ;
if(!rejected_date($weldLog->welding_date)) {
$testPackagesSummary[$weldLog->test_package_no]['total_complated_field_wdi'] += $wdi;
$testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no]['total_complated_field_wdi'] += $wdi;
}
}
if($weldLog->type_of_joint == "S") {
$testPackagesSummary[$weldLog->test_package_no]['total_shop_wdi'] += $wdi;
$testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no]['total_shop_wdi'] += $wdi;
if(!rejected_date($weldLog->welding_date)) {
$testPackagesSummary[$weldLog->test_package_no]['total_complated_shop_wdi'] += $wdi;
$testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no]['total_complated_shop_wdi'] += $wdi;
}
}
if(!rejected_date($weldLog->welding_date)) {
$testPackagesSummary[$weldLog->test_package_no]['total_complated_wdi'] += $wdi;
$testPackagesIsoSummary[$weldLog->iso_number][$weldLog->test_package_no]['total_complated_wdi'] += $wdi;
}
// Welding progress hesaplama
$totalWdi = $testPackagesSummary[$weldLog->test_package_no]['total_wdi'];
$totalComplatedWdi = $testPackagesSummary[$weldLog->test_package_no]['total_complated_wdi'];
if ($totalWdi > 0) {
$testPackagesSummary[$weldLog->test_package_no]['welding_progress'] =
round(($totalComplatedWdi * 100) / $totalWdi, 2);
} else {
$testPackagesSummary[$weldLog->test_package_no]['welding_progress'] = 0;
}
}
TransactionHelper::retryTransaction(function () use ($testPackagesIsoSummary, $repairLogsSummary, $repairLogsSummaryCompleted, $repairLogsSummaryRemaining, $repairLogsSummary2, $repairLogsSummaryCompleted2, $repairLogsSummaryRemaining2) {
foreach($testPackagesIsoSummary AS $isoNumber => $data) {
foreach($data AS $tpNo => $data2) {
if($data2['total_complated_wdi'] == $data2['total_wdi']) {
$status = "Completed";
}
if($data2['total_complated_wdi'] < $data2['total_wdi']) {
$status = "On Going";
}
if($data2['total_complated_wdi'] == 0) {
$status = "Waiting";
}
$updateData = [
'welding_status' => $status,
'repair_qty' => @$repairLogsSummary[$isoNumber][$tpNo],
'repair_completed' => @$repairLogsSummaryCompleted[$isoNumber][$tpNo],
'repair_remaining' => @$repairLogsSummaryRemaining[$isoNumber][$tpNo],
];
db("test_pack_base_statuses")
->where("drawing_no", $isoNumber)
->where("test_package_no", $tpNo)
->update($updateData);
$updateData = [
'welding_status' => $status,
'repair_qty' => @$repairLogsSummary2[$tpNo],
'repair_completed' => @$repairLogsSummaryCompleted2[$tpNo],
'repair_remaining' => @$repairLogsSummaryRemaining2[$tpNo],
];
db("test_packages")
->where("test_package_number", $tpNo)
->update($updateData);
}
}
}, 5);
TransactionHelper::retryTransaction(function () use ($testPackagesSummary, $repairLogsSummary2) {
foreach($testPackagesSummary AS $tpNo => $data2) {
if($data2['total_complated_wdi'] == $data2['total_wdi']) {
$status = "Completed";
}
if($data2['total_complated_wdi'] < $data2['total_wdi']) {
$status = "On Going";
}
if($data2['total_complated_wdi'] == 0) {
$status = "Waiting";
}
db("test_packages")
->where("test_package_number", $tpNo)
->update([
'welding_status' => $status,
'repair_status_total' => @$repairLogsSummary2[$tpNo]
]);
}
}, 5);
TransactionHelper::retryTransaction(function () use ($testPackages, $testPackagesSummary, $totalFields) {
$k = 0;
foreach($testPackages AS $testPackage) {
$updateData = [];
if(isset($testPackagesSummary[$testPackage->test_package_number])) {
foreach($totalFields AS $field) {
$testPackage->$field = $testPackagesSummary[$testPackage->test_package_number][$field];
$updateData[$field] = $testPackagesSummary[$testPackage->test_package_number][$field];
}
}
$updateData = array_merge($updateData, updateTestPackageStatus($testPackage));
db("test_packages")->where("id", $testPackage->id)
->update($updateData);
db("test_pack_base_statuses")->where("test_package_no", $testPackage->test_package_number)
->update([
'tp_status' => $updateData['status'] ?? 'Waiting',
'priority' => $testPackage->priority,
'priority_info' => $testPackage->priority_info,
'responsible_person' => $testPackage->responsible_test,
'target_test_date' => $testPackage->planned_test_date,
]);
$k++;
}
return $k;
}, 5);
//dump("$k Test Pack Status Changer Processed ");
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [10/12] Test Pack Base Status Changer - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Test Pack Base Status Changer',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3)
]);
}
// Paint Follow Ups Sync - Based on weld_logs data
if ($shouldRunPaintFollowUpUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [11/12] Paint Follow Ups Sync - STARTED", [
'weld_log_id' => $id,
'process' => 'Paint Follow Ups Sync'
]);
try {
// Mevcut weld_log verisini al
$weldLog = db("weld_logs")->where("id", $id)->first();
if ($weldLog) {
// Gerekli alanlar boşsa işlemi atla
if (empty($weldLog->line_number)) {
return;
}
// Aynı line_number'a sahip tüm weld_logs kayıtlarını getir
$allWeldLogs = db("weld_logs")
->where("line_number", $weldLog->line_number)
->orderBy('id', 'ASC') // Deadlock prevention
->get();
// Her bir weld log için işlemi gerçekleştir
$paintFollowUpCreated = 0;
$paintFollowUpUpdated = 0;
// Paint Follow Up işlemlerini chunk'lara böl ve TransactionHelper ile işle
TransactionHelper::chunkTransaction(
$allWeldLogs,
function ($paintWeldLogChunk) use (&$paintFollowUpCreated, &$paintFollowUpUpdated) {
foreach ($paintWeldLogChunk as $currentWeldLog) {
// Gerekli alan kontrolü
if (empty($currentWeldLog->fluid_code)) {
//dump("Kayıt için Paint Follow Ups senkronizasyonu atlanıyor - fluid_code eksik");
continue;
}
// Line list ve Paint Matrix verilerini al
$lineList = db("line_lists")
->where('line_no', $currentWeldLog->line_number)
->first();
$paintMatrix = PaintMatrix::where('line', $currentWeldLog->line_number)
->where('fluid_code', $currentWeldLog->fluid_code)
->first();
if (!$paintMatrix) {
//dump("Kayıt için Paint Follow Ups senkronizasyonu atlanıyor - bu line/fluid code için paint matrix bulunamadı");
continue;
}
// Paint Follow Up için temel veri
$basePaintFollowUpData = [
// Proje Bilgileri
'project' => $currentWeldLog->project ?? '',
'description' => $paintMatrix->description ?? '',
'area' => $currentWeldLog->design_area ?? '',
// Hat Bilgileri
'line' => $currentWeldLog->line_number,
'iso_number' => $currentWeldLog->iso_number ?? '',
'fluid_code' => $currentWeldLog->fluid_code ?? '',
'fluid_code_description' => $lineList->fluid_ru ?? '',
// Boya bilgileri
'cycle' => $paintMatrix->paint_cycle ?? '',
// Primer coat bilgileri
'primer_coat_name_1' => $paintMatrix->primer_coat ?? '',
'brend_name_1' => $paintMatrix->brend_name_1 ?? '',
'colour_1' => $paintMatrix->colour_1 ?? '',
'ral_code_1' => $paintMatrix->ral_code_1 ?? '',
'thickness_1' => $paintMatrix->thickness_1 ?? '',
// Intermediate coat bilgileri
'intermediate_coat_name_2' => $paintMatrix->intermediate_coat ?? '',
'brend_name_2' => $paintMatrix->brend_name_2 ?? '',
'colour_2' => $paintMatrix->colour_2 ?? '',
'ral_code_2' => $paintMatrix->ral_code_2 ?? '',
'thickness_2' => $paintMatrix->thickness_2 ?? '',
// Final coat bilgileri
'final_coat_name_3' => $paintMatrix->final_coat ?? '',
'brend_name_3' => $paintMatrix->brend_name_3 ?? '',
'colour_3' => $paintMatrix->colour_3 ?? '',
'ral_code_3' => $paintMatrix->ral_code_3 ?? '',
'thickness_3' => $paintMatrix->thickness_3 ?? '',
// Durum bilgileri
'status' => 'In Progress',
'updated_at' => now()
];
// Line number üzerinde en az bir S tipi joint varlığını kontrol et
$hasShopJoint = db("weld_logs")
->where('line_number', $currentWeldLog->line_number)
->where('spool_number', $currentWeldLog->spool_number)
->where('type_of_joint', 'S')
->exists();
// SHOP kaydı için - spool_number kullanılır
if ($hasShopJoint && !empty($currentWeldLog->spool_number)) {
$shopData = $basePaintFollowUpData;
$shopData['location'] = 'SHOP';
$shopData['spool_no_joint_no'] = $currentWeldLog->spool_number;
// Where koşulu
$shopWhereCondition = [
'line' => $currentWeldLog->line_number,
// 'fluid_code' => $currentWeldLog->fluid_code,
'spool_no_joint_no' => $currentWeldLog->spool_number,
// 'location' => 'SHOP'
];
// Mevcut kayıt var mı kontrolü
$existingShopRecord = db("paint_follow_ups")
->where($shopWhereCondition)
->first();
if ($existingShopRecord) {
// Mevcut kaydı güncelle
db("paint_follow_ups")
->where('id', $existingShopRecord->id)
->update($shopData);
$paintFollowUpUpdated++;
} else {
// Yeni kayıt oluştur
$shopData['created_at'] = now();
db("paint_follow_ups")->insert($shopData);
$paintFollowUpCreated++;
}
}
// FIELD kaydı için - no_of_the_joint_as_per_as_built_survey kullanılır
if (!empty($currentWeldLog->no_of_the_joint_as_per_as_built_survey)) {
// Joint numarası için repair kontrol et
$jointNo = $currentWeldLog->no_of_the_joint_as_per_as_built_survey;
$jointType = "Normal";
if(strpos($jointNo, "R") !== false) {
$jointType = "Repair";
}
$fieldData = $basePaintFollowUpData;
$fieldData['location'] = 'FIELD';
$fieldData['spool_no_joint_no'] = $jointNo;
// Where koşulu
$fieldWhereCondition = [
'line' => $currentWeldLog->line_number,
'fluid_code' => $currentWeldLog->fluid_code,
'spool_no_joint_no' => $jointNo,
'location' => 'FIELD'
];
// Mevcut kayıt var mı kontrolü
$existingFieldRecord = db("paint_follow_ups")
->where($fieldWhereCondition)
->first();
if ($existingFieldRecord) {
// Mevcut kaydı güncelle
db("paint_follow_ups")
->where('id', $existingFieldRecord->id)
->update($fieldData);
$paintFollowUpUpdated++;
} else {
// Yeni kayıt oluştur
$fieldData['created_at'] = now();
db("paint_follow_ups")->insert($fieldData);
$paintFollowUpCreated++;
}
}
}
return $paintWeldLogChunk->count();
},
10, // Chunk size increased from 3 to 10 for better performance
10000 // 10ms delay (reduced from 150ms) - sufficient for deadlock prevention
);
}
} catch (\Throwable $th) {
Log::error("Paint Follow Ups senkronizasyon hatası: " . $th->getMessage());
// Hata ayıklama için detaylı bilgi
Log::error("Hata detayları: ", [
'weldLogId' => $id,
'exception' => get_class($th),
'file' => $th->getFile(),
'line' => $th->getLine(),
'trace' => $th->getTraceAsString()
]);
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [11/12] Paint Follow Ups Sync - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Paint Follow Ups Sync',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3),
'created' => $paintFollowUpCreated,
'updated' => $paintFollowUpUpdated
]);
}
// Handovers Sync - Based on weld_logs data
if ($shouldRunHandoverUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [12/12] Handovers Sync - STARTED", [
'weld_log_id' => $id,
'process' => 'Handovers Sync'
]);
try {
// Mevcut weld_log verisini al
$weldLog = db("weld_logs")->where("id", $id)->first();
if ($weldLog) {
// Gerekli alanlar boşsa işlemi atla
if (empty($weldLog->line_number)) {
return;
}
// Aynı line_number'a sahip tüm weld_logs kayıtlarını getir
$allWeldLogs = db("weld_logs")
->where("line_number", $weldLog->line_number)
->orderBy('id', 'ASC') // Deadlock prevention
->get();
// Her bir weld log için işlemi gerçekleştir
$handoversCreated = 0;
$handoversUpdated = 0;
// Line'a göre gruplama yapıyoruz çünkü handovers line bazında tutulur
$uniqueLines = [];
foreach ($allWeldLogs as $currentWeldLog) {
$lineKey = $currentWeldLog->line_number;
if (!isset($uniqueLines[$lineKey])) {
$uniqueLines[$lineKey] = $currentWeldLog;
}
}
// Handovers işlemlerini chunk'lara böl ve TransactionHelper ile işle
TransactionHelper::chunkTransaction(
collect($uniqueLines),
function ($handoverChunk) use (&$handoversCreated, &$handoversUpdated) {
foreach ($handoverChunk as $currentWeldLog) {
// Gerekli alan kontrolü
if (empty($currentWeldLog->line_number)) {
//dump("Kayıt için Handovers senkronizasyonu atlanıyor - line_number eksik");
continue;
}
// Line list verilerini al (ek bilgiler için)
$lineList = db("line_lists")
->where('line_no', $currentWeldLog->line_number)
->first();
// Handovers için temel veri
$handoverData = [
// Mapping: weld_logs -> handovers
'project' => $currentWeldLog->line_number, // line_number -> location (zone yerine)
'work_type' => 'ТРУБКА', // piping_type -> work_type
'object' => $currentWeldLog->project ?? '', // project -> object
'location' => $currentWeldLog->design_area ?? '', // design_area -> project
// Durum bilgileri
'status1' => 'In Progress',
'updated_at' => now()
];
// Where koşulu - location (line_number) ve object (project) ile unique kayıt
$whereCondition = [
'project' => $currentWeldLog->line_number,
// 'object' => $currentWeldLog->project ?? ''
];
// Mevcut kayıt var mı kontrolü
$existingRecord = db("handovers")
->where($whereCondition)
->first();
if ($existingRecord) {
// Mevcut kaydı güncelle
db("handovers")
->where('id', $existingRecord->id)
->update($handoverData);
$handoversUpdated++;
// dump("Handover kaydı güncellendi: Location {$currentWeldLog->line_number}");
} else {
// Yeni kayıt oluştur
$handoverData['created_at'] = now();
db("handovers")->insert($handoverData);
$handoversCreated++;
}
}
return $handoverChunk->count();
},
10, // Chunk size increased from 3 to 10 for better performance
10000 // 10ms delay (reduced from 150ms) - sufficient for deadlock prevention
);
}
} catch (\Throwable $th) {
Log::error("Handovers senkronizasyon hatası: " . $th->getMessage());
// Hata ayıklama için detaylı bilgi
Log::error("Hata detayları: ", [
'weldLogId' => $id,
'exception' => get_class($th),
'file' => $th->getFile(),
'line' => $th->getLine(),
'trace' => $th->getTraceAsString()
]);
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [12/12] Handovers Sync - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Handovers Sync',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3),
'created' => $handoversCreated,
'updated' => $handoversUpdated
]);
}
if($shouldRunTestPackageUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [13/13] Test Pack Cleanup - STARTED", [
'weld_log_id' => $id,
'process' => 'Test Pack Cleanup'
]);
try {
$result = view('cron.weld_logs-delete-non-matching-test-pack-statuses')->render();
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [13/13] Test Pack Cleanup - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Test Pack Cleanup',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3),
'result' => 'success'
]);
} catch (\Throwable $th) {
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::error("WeldLog Trigger [13/13] Test Pack Cleanup - FAILED (non-critical)", [
'weld_log_id' => $id,
'process' => 'Test Pack Cleanup',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3),
'error' => $th->getMessage(),
'file' => $th->getFile(),
'line' => $th->getLine()
]);
// This is a non-critical operation, continue execution
}
/*
$beforeTestPackNo = $beforeData->test_package_no;
if($beforeTestPackNo != $refactoringData['test_package_no']) {
$testPackWhereData = [
'test_package_number' => $beforeTestPackNo
];
$testPackBaseStatusWhereData = [
'test_package_no' => $beforeTestPackNo,
'drawing_no' => $data->iso_number,
];
$testPackagesChanged = db("test_packages")
->where($testPackWhereData)
->update(["test_package_number"=> $refactoringData['test_package_no']]);
$tpBaseChanged = db("test_pack_base_statuses")
->where($testPackBaseStatusWhereData)
->update(["test_package_no" => $refactoringData['test_package_no']]);
}
*/
}
// Test Package işlemleri
if ($shouldRunTestPackageUpdate) {
$processStartTime = microtime(true);
Log::info("WeldLog Trigger [7/12] Test Package Operations - STARTED", [
'weld_log_id' => $id,
'process' => 'Test Package Operations'
]);
$weldLogs = db("weld_logs")->orderBy("test_package_no", "DESC");
$weldLogs = $weldLogs
->where("iso_number", $data->iso_number)
->where("test_package_no", $data->test_package_no);
$weldLogs = $weldLogs->get();
$repairLogs = db("repair_logs")->where("iso_number", $data->iso_number)
->where("test_package_no", $data->test_package_no)->get();
$supports = db("supports")
->where("line_number", $data->line_number)
->get();
// Update supports weld_or_assembled_date when welding_date is available
if (!empty($data->welding_date) && !empty($data->line_number)) {
db("supports")
->where("line_number", $data->line_number)
->where(function($query) use ($data) {
$query->where("support_code", $data->element_code_1)
->orWhere("support_code", $data->element_code_2);
})
->update([
"weld_or_assembled_date" => $data->welding_date
]);
}
$punchLists = PunchList::where("line_isometric_no", $data->line_number)->where("test_package", $data->test_package_no)->get();
$logTypes = array_keys(log_test_types());
$testTypeToMedium = [
'PNEUMATIC' => 'Air',
'HYDRAULIC' => 'Water',
'VISUAL' => '-',
'ACUISTIC' => '-',
];
TestPackage::orWhere("test_package_number", "")->orWhereNull("test_package_number")->delete();
TestPackBaseStatus::orWhere("test_package_no", "")->orWhereNull("test_package_no")->delete();
$weldLogTestPackCount = 0;
$supportStats = [];
$supportStatsTP = [];
foreach($supports AS $support)
{
$tpNo = @$isoToTP[$support->line_number];
if(!isset($supportStatsTP[$tpNo]['support_remaining']))
{
$supportStatsTP[$tpNo]['support_remaining'] = 0;
$supportStatsTP[$tpNo]['welded_support_quantity'] = 0;
$supportStatsTP[$tpNo]['support_progress'] = 0;
}
if(!isset($supportStats[$support->line_number]['support_remaining']))
$supportStats[$support->line_number]['support_remaining'] = 0;
if(!isset($supportStats[$support->line_number]['welded_support_quantity']))
$supportStats[$support->line_number]['welded_support_quantity'] = 0;
if(!isset($supportStats[$support->line_number]['support_progress']))
$supportStats[$support->line_number]['support_progress'] = 0;
if(!rejected_date($support->weld_or_assembled_date) && $support->erection_type == "Weld")
{
$supportStats[$support->line_number]['welded_support_quantity']+= $support->quantity;
$supportStatsTP[$tpNo]['welded_support_quantity']+= $support->quantity;
} else {
$supportStats[$support->line_number]['support_remaining']+= $support->quantity;
$supportStatsTP[$tpNo]['support_remaining']+= $support->quantity;
}
if($supportStats[$support->line_number]['welded_support_quantity'] > 0) {
$supportStats[$support->line_number]['support_progress'] =
100 - ($supportStats[$support->line_number]['support_remaining'] * 100) /
($supportStats[$support->line_number]['welded_support_quantity'] + $supportStats[$support->line_number]['support_remaining']);
} else {
$supportStats[$support->line_number]['support_progress'] = 0; // Eğer welded_support_quantity sıfırsa
}
if($supportStatsTP[$tpNo]['welded_support_quantity'] > 0) {
$supportStatsTP[$tpNo]['support_progress'] =
100 - ($supportStatsTP[$tpNo]['support_remaining'] * 100) /
($supportStatsTP[$tpNo]['welded_support_quantity'] + $supportStatsTP[$tpNo]['support_remaining']);
} else {
$supportStatsTP[$tpNo]['support_progress'] = 0; // Eğer welded_support_quantity sıfırsa
}
}
$stats = [];
$quantity_of_iso = [];
$punchListNumbers = [];
foreach($punchLists AS $punchList) {
$drawingNo = $punchList->line_isometric_no;
if(!isset($stats[$drawingNo][$punchList->test_package]['punch_a_quantity']))
$stats[$drawingNo][$punchList->test_package]['punch_a_quantity'] = 0;
if(!isset($stats[$drawingNo][$punchList->test_package]['punch_b_quantity']))
$stats[$drawingNo][$punchList->test_package]['punch_b_quantity'] = 0;
if(!isset($stats[$drawingNo][$punchList->test_package]['punch_c_quantity']))
$stats[$drawingNo][$punchList->test_package]['punch_c_quantity'] = 0;
if(!isset($punchListNumbers[$punchList->test_package]))
$punchListNumbers[$punchList->test_package] = [];
if(!in_array($punchList->punch_list_no, $punchListNumbers[$punchList->test_package]))
$punchListNumbers[$punchList->test_package][] = $punchList->punch_list_no;
if(!isset($stats[$punchList->test_package]['punch_a_open_quantity']))
$stats[$punchList->test_package]['punch_a_open_quantity'] = 0;
if(!isset($stats[$punchList->test_package]['punch_b_open_quantity']))
$stats[$punchList->test_package]['punch_b_open_quantity'] = 0;
if(!isset($stats[$punchList->test_package]['punch_c_open_quantity']))
$stats[$punchList->test_package]['punch_c_open_quantity'] = 0;
if($punchList->category == "A") {
if($punchList->status == "Open") {
$stats[$punchList->test_package]['punch_a_open_quantity']++;
}
$stats[$drawingNo][$punchList->test_package]['punch_a_quantity']++;
}
if($punchList->category == "B") {
if($punchList->status == "Open") {
$stats[$punchList->test_package]['punch_b_open_quantity']++;
}
$stats[$drawingNo][$punchList->test_package]['punch_b_quantity']++;
}
if($punchList->category == "C") {
if($punchList->status == "Open") {
$stats[$punchList->test_package]['punch_c_open_quantity']++;
}
$stats[$drawingNo][$punchList->test_package]['punch_c_quantity']++;
}
$stats[$punchList->test_package]['found_date'] = $punchList->found_date;
$stats[$punchList->test_package]['punch_list'] = $punchList->punch_list;
}
$addedSheet = [];
foreach($weldLogs AS $weldLog) {
$jointNo = $weldLog->no_of_the_joint_as_per_as_built_survey;
$goldenJoints = 0;
$goldenJoints2 = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['goldenJoints']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['goldenJoints'] = 0;
if(!isset($quantity_of_iso[$weldLog->test_package_no]['total_qty']))
$quantity_of_iso[$weldLog->test_package_no]['total_qty'] = 0;
if(!isset($addedSheet[$weldLog->test_package_no]))
$addedSheet[$weldLog->test_package_no] = [];
if(!in_array($weldLog->quantity_of_iso, $addedSheet[$weldLog->test_package_no])) {
$quantity_of_iso[$weldLog->test_package_no]['total_qty']++;
$addedSheet[$weldLog->test_package_no][] = $weldLog->quantity_of_iso;
}
if(!isset($quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_qty']))
$quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_qty'] = 0;
if(!isset($addedSheet[$weldLog->iso_number][$weldLog->test_package_no]))
$addedSheet[$weldLog->iso_number][$weldLog->test_package_no] = [];
if(!in_array($weldLog->quantity_of_iso, $addedSheet[$weldLog->iso_number][$weldLog->test_package_no])) {
$quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_qty']++;
$addedSheet[$weldLog->iso_number][$weldLog->test_package_no][] = $weldLog->quantity_of_iso;
}
if(!isset($stats[$weldLog->test_package_no]['goldenJoints']))
$stats[$weldLog->test_package_no]['goldenJoints'] = 0;
if(strpos(strtoupper($jointNo), "GJ") !== false) {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['goldenJoints']++;
$stats[$weldLog->test_package_no]['goldenJoints']++;
}
if(!isset($quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_iso_quantity']))
$quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_iso_quantity'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['rt_ut_status']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['rt_ut_status'] = 0;
$backlogs = [
'rt_backlog',
'ut_backlog',
'mt_backlog',
'pmi_backlog',
'vt_backlog',
'pt_backlog',
'ferrit_backlog',
'pwht_backlog',
'total_backlog',
];
foreach($backlogs AS $backlog)
{
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no][$backlog]))
$stats[$weldLog->iso_number][$weldLog->test_package_no][$backlog] = 0;
if(!isset($stats[$weldLog->test_package_no][$backlog]))
$stats[$weldLog->test_package_no][$backlog] = 0;
}
if(!isset($stats[$weldLog->test_package_no]['total_backlog']))
$stats[$weldLog->test_package_no]['total_backlog'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['rt_ut_done']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['rt_ut_done'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_pt_backlog']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_pt_backlog'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_pt_done']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_pt_done'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['remaining_wdi']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['remaining_wdi'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['total_wdi']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_wdi'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['total_complated_wdi']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_complated_wdi'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['total_joint_qty']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_joint_qty'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['total_welded_joint_qty']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_welded_joint_qty'] = 0;
if(!isset($stats[$weldLog->iso_number][$weldLog->test_package_no]['welded_support_quantity']))
$stats[$weldLog->iso_number][$weldLog->test_package_no]['welded_support_quantity'] = 0;
foreach($logTypes AS $logType) {
$weldLogArray = (Array) $weldLog;
$stats[$weldLog->test_package_no]['total_backlog'] += (float) $weldLogArray[$logType . "_scope"];
}
if(!isset($addedSheet[$weldLog->iso_number][$weldLog->test_package_no]['total_iso']))
$addedSheet[$weldLog->iso_number][$weldLog->test_package_no]['total_iso'] = [];
if(!in_array($weldLog->quantity_of_iso, $addedSheet[$weldLog->iso_number][$weldLog->test_package_no]['total_iso']))
{
$quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_iso_quantity']++;
$addedSheet[$weldLog->iso_number][$weldLog->test_package_no]['total_iso'][] = $weldLog->quantity_of_iso;
}
//welded_support_quantity
if(rejected_date($weldLog->welding_date)) {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['remaining_wdi'] += (float) $weldLog->nps_1;
}
if(!rejected_date($weldLog->rt_test_date)) {
// $stats[$weldLog->iso_number][$weldLog->test_package_no]['rt_ut_done']++;
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['rt_backlog']++;
$stats[$weldLog->test_package_no]['rt_backlog']++;
}
if(!rejected_date($weldLog->ut_test_date)) {
// $stats[$weldLog->iso_number][$weldLog->test_package_no]['rt_ut_done']++;
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['ut_backlog'] ++;
$stats[$weldLog->test_package_no]['ut_backlog'] ++;
}
if(!rejected_date($weldLog->pwht_test_date)) {
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['pwht_backlog']++;
$stats[$weldLog->test_package_no]['pwht_backlog']++;
}
if(!rejected_date($weldLog->pmi_test_date)) {
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['pmi_backlog']++;
$stats[$weldLog->test_package_no]['pmi_backlog']++;
}
if(!rejected_date($weldLog->ferrite_test_date)) {
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['ferrit_backlog']++;
$stats[$weldLog->test_package_no]['ferrit_backlog']++;
}
if(!rejected_date($weldLog->pt_test_date)) {
//$stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_pt_done']++;
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['pt_backlog']++;
$stats[$weldLog->test_package_no]['pt_backlog']++;
}
if(!rejected_date($weldLog->mt_test_date)) {
//$stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_pt_done']++;
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_backlog']++;
$stats[$weldLog->test_package_no]['mt_backlog']++;
}
if(!rejected_date($weldLog->vt_test_date)) {
//$stats[$weldLog->iso_number][$weldLog->test_package_no]['mt_pt_done']++;
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['vt_backlog']++;
$stats[$weldLog->test_package_no]['vt_backlog']++;
}
if(!rejected_date($weldLog->welding_date)) {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_complated_wdi'] += (float) $weldLog->nps_1;
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_welded_joint_qty']++;
}
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_wdi'] += (float) $weldLog->nps_1;
// Welding progress hesaplama - ISO bazlı stats kullanılıyor
$totalWdi = $stats[$weldLog->iso_number][$weldLog->test_package_no]['total_wdi'];
$totalComplatedWdi = $stats[$weldLog->iso_number][$weldLog->test_package_no]['total_complated_wdi'];
if ($totalWdi > 0) {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['welding_progress'] =
round(($totalComplatedWdi * 100) / $totalWdi, 2);
} else {
$stats[$weldLog->iso_number][$weldLog->test_package_no]['welding_progress'] = 0;
}
$stats[$weldLog->iso_number][$weldLog->test_package_no]['total_joint_qty'] ++;
}
$ndtCalculation = j(view('admin-ajax.ndt-calculation', [
'test_package_no' => $data->test_package_no,
'iso_number2' => $data->iso_number,
'type' => 'test_packs',
])->render());
$tpStats = $ndtCalculation['tpStats'];
$tpIsoStats = $ndtCalculation['tpISOStats'];
// Test Package işlemlerini chunk'lara böl ve TransactionHelper ile işle
TransactionHelper::chunkTransaction(
$weldLogs,
function ($weldLogChunk) use ($punchListNumbers, $stats, $tpStats, $tpIsoStats, $supportStatsTP, $quantity_of_iso, $testTypeToMedium, $supportStats, &$weldLogTestPackCount) {
foreach($weldLogChunk as $weldLog) {
try {
$punchListData = implode(",", $punchListNumbers[$weldLog->test_package_no]);
} catch (\Throwable $th) {
$punchListData = "";
}
$thisStats = @$stats[$weldLog->test_package_no];
$thisTpStats = @$tpStats[$weldLog->test_package_no];
$thisTpISOStats = @$tpIsoStats[$weldLog->test_package_no][$weldLog->iso_number];
$thisSupportStats = @$supportStatsTP[$weldLog->test_package_no];
$thisTotalBacklog =
(@$thisTpStats['vt'] ?? 0) +
(@$thisTpStats['ut'] ?? 0) +
(@$thisTpStats['mt'] ?? 0) +
(@$thisTpStats['pmi'] ?? 0) +
(@$thisTpStats['pt'] ?? 0) +
(@$thisTpStats['rt'] ?? 0) +
(@$thisTpStats['pwht'] ?? 0) +
(@$thisTpStats['ferrite'] ?? 0);
$testPackageData = [
'unit' => $weldLog->design_area,
'test_package_number' => $weldLog->test_package_no,
'discipline' => $weldLog->piping_type,
'circuit_number' => $weldLog->circuit_number,
'p_id' => $weldLog->p_id,
'iso_quantity' => $quantity_of_iso[$weldLog->test_package_no]['total_qty'],//$weldLog->quantity_of_iso, //burada qty toplam sayı gelmeli
// 'subcontractor' => $weldLog->ste_subcontractor,
'test_type' => $weldLog->type_of_test,
'test_medium' => @$testTypeToMedium[strtoupper($weldLog->type_of_test)],
'test_pressure' => $weldLog->test_pressure,
'golden_joints' => @$stats[$weldLog->iso_number][$weldLog->test_package_no]['goldenJoints'],
'walkdown_date' => @$stats[$weldLog->iso_number][$weldLog->test_package_no]['found_date'],
'punch_list' => $punchListData,
'welded_support_quantity' => @$thisSupportStats['welded_support_quantity'],
'support_remaining' => @$thisSupportStats['support_remaining'],
'support_progress' => @$thisSupportStats['support_progress'],
'a_punch_point_open' => @$stats[$weldLog->iso_number][$weldLog->test_package_no]['punch_a_open_quantity'],
'b_punch_point_open' => @$stats[$weldLog->iso_number][$weldLog->test_package_no]['punch_b_open_quantity'],
'c_punch_point_open' => @$stats[$weldLog->iso_number][$weldLog->test_package_no]['punch_c_open_quantity'],
'vt_backlog' => @$thisTpStats['vt'],
'ut_backlog' => @$thisTpStats['ut'],
'mt_backlog' => @$thisTpStats['mt'],
'pmi_backlog' => @$thisTpStats['pmi'],
'pt_backlog' => @$thisTpStats['pt'],
'rt_backlog' => @$thisTpStats['rt'],
'pwht_backlog' => @$thisTpStats['pwht'],
'ferrit_backlog' => @$thisTpStats['ferrite'],
'ndt_status' => @$thisTotalBacklog == 0 ? "Completed" : "Not Completed",
'welding_progress' => @$stats[$weldLog->iso_number][$weldLog->test_package_no]['welding_progress'],
];
$thisStats = @$stats[$weldLog->iso_number][$weldLog->test_package_no];
$thisSupportStats = @$supportStats[$weldLog->iso_number];
try {
$pipeProgress = round($thisStats['total_complated_wdi'] * 100 / $thisStats['total_wdi'], 2);
} catch (\Throwable $th) {
$pipeProgress = 0;
}
$testPackBaseStatusData = [
'area' => $weldLog->project,
'drawing_no' => $weldLog->iso_number,
'test_package_no' => $weldLog->test_package_no,
'discipline' => $weldLog->piping_type,
'iso_qty' => $quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_qty'], //burada qty toplam sayı gelmeli
// 'subcontractor' => $weldLog->ste_subcontractor,
'test_type' => $weldLog->type_of_test,
'test_medium' => @$testTypeToMedium[strtoupper($weldLog->type_of_test)],
'test_pressure_mpa' => $weldLog->test_pressure,
'tp_status' => '', // bu data test pack base stat. girilecek
'total_iso_quantity' => $quantity_of_iso[$weldLog->iso_number][$weldLog->test_package_no]['total_iso_quantity'],
// 'welding_status' => '',
'remaining_wdi' => $thisStats['remaining_wdi'],
'total_wdi' => $thisStats['total_wdi'],
'total_complated_wdi' => $thisStats['total_complated_wdi'],
'pipe_progress' => $pipeProgress,
'total_joint_qty' => $thisStats['total_joint_qty'],
'total_welded_joint_qty' => $thisStats['total_welded_joint_qty'],
'welded_support_quantity' => @$thisSupportStats['welded_support_quantity'],
'support_remaining' => @$thisSupportStats['support_remaining'],
'support_progress' => @$thisSupportStats['support_progress'],
'punch_a_quantity' => @$thisStats['punch_a_quantity'], //punch listteki a lar
'punch_b_quantity' => @$thisStats['punch_b_quantity'],
'punch_c_quantity' => @$thisStats['punch_c_quantity'],
// 'repair_qty' => $repairQty,
'rt_ut_status' => $thisStats['rt_ut_status'],
'rt_backlog' => @$thisTpISOStats['rt'],
'ut_backlog' => @$thisTpISOStats['ut'],
'mt_backlog' => @$thisTpISOStats['mt'],
'pmi_backlog' => @$thisTpISOStats['pmi'],
'vt_backlog' => @$thisTpISOStats['vt'],
'pt_backlog' => @$thisTpISOStats['pt'],
'pwht_backlog' => @$thisTpISOStats['pwht'],
'ferrit_backlog' => @$thisTpISOStats['ferrite'],
];
$testPackWhereData = [
'test_package_number' => $weldLog->test_package_no
];
$testPackBaseStatusWhereData = [
'test_package_no' => $weldLog->test_package_no,
'drawing_no' => $weldLog->iso_number,
];
if($weldLog->test_package_no != "" && !is_null($weldLog->test_package_no)) {
$testPackResult = TestPackage::updateOrCreate($testPackWhereData, $testPackageData);
$testPackBaseResult = TestPackBaseStatus::updateOrCreate($testPackBaseStatusWhereData, $testPackBaseStatusData);
$weldLogTestPackCount++;
}
}
return $weldLogChunk->count();
},
50, // Chunk size increased from 3 to 10 for better performance
1000 // 10ms delay (reduced from 200ms) - sufficient for deadlock prevention
);
//dump("$weldLogTestPackCount Data has been sync from WeldLog ==> Test Packages");
// Sync weld logs to test packages for this specific test package
try {
if(isset($weldLog->test_package_no) && $weldLog->test_package_no != "") {
$syncParams = [
'test_package_no' => $weldLog->test_package_no
];
$syncResult = view('cron.weld_logs-sync-from-weldlog-to-test-pack', $syncParams)->render();
Log::debug("Weld logs sync completed for test package: " . $weldLog->test_package_no);
}
} catch (\Throwable $th) {
Log::error("Weld logs sync failed for test package: " . $weldLog->test_package_no . " - " . $th->getMessage());
}
$processEndTime = microtime(true);
$processDuration = round(($processEndTime - $processStartTime) * 1000, 2);
Log::info("WeldLog Trigger [7/12] Test Package Operations - COMPLETED", [
'weld_log_id' => $id,
'process' => 'Test Package Operations',
'duration_ms' => $processDuration,
'duration_sec' => round($processDuration / 1000, 3)
]);
}
?>