Files
sam-kd/output/viewScreenWork.php
hskwon aca1767eb9 초기 커밋: 5130 레거시 시스템
- URL 하드코딩 → .env APP_URL 기반 동적 URL로 변경
- DB 연결 하드코딩 → .env 기반으로 변경
- MySQL strict mode DATE 오류 수정
2025-12-10 20:14:31 +09:00

1232 lines
46 KiB
PHP

<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
/* // 3) 공차를 적용한 규격 계산 (900, 800, 600, 400, 300) 추가 2025/06/16 스크린실 및 노완호차장 요청
*/
$title_message = '스크린 작업일지';
$tablename = 'output';
$item ='스크린 작업일지';
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
include $_SERVER['DOCUMENT_ROOT'] . '/output/common/function.php'; // 스크린절단사이즈 함수 불러오기
// 품질담당자 및 관리자인 경우 권한 부여
$QCadmin = false ;
if($user_name=='이세희' || $user_name=='개발자' || $user_name=='함신옥')
$QCadmin = true ;
?>
<title> <?=$title_message?> </title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php
// JavaScript에서 전달된 변수들 받기
$num = isset($_REQUEST['num']) ? $_REQUEST['num'] : '';
try {
$sql = "select * from {$DB}.{$tablename} where num = ? ";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $num, PDO::PARAM_STR);
$stmh->execute();
$count = $stmh->rowCount();
if ($count < 1) {
print "검색결과가 없습니다.<br>";
} else {
$row = $stmh->fetch(PDO::FETCH_ASSOC);
include "_row.php";
// output_extra 테이블에서 데이터 불러오기
require_once $_SERVER['DOCUMENT_ROOT'] . '/output/load_output_extraTable.php';
}
} catch (PDOException $Exception) {
print "오류: " . $Exception->getMessage();
}
// JSON 문자열을 PHP 배열로 디코딩합니다.
//스크린발주서 읽기
$eList = json_decode($estimateList, true);
// 데이터베이스에서 recordscreen 컬럼 값을 가져온 후 디코딩
$recordscreen = isset($recordscreen) ? json_decode($recordscreen, true) : [];
// JSON 데이터를 JavaScript 변수로 변환
echo "<script>";
echo "var recordscreenData = " . json_encode($recordscreen) . ";";
echo "</script>";
if (is_array($eList) && count($eList) > 0) {
foreach ($eList as $row) {
if(strpos($row['col5'], '실리') !== false)
$item_name = '실리카원단';
else if(strpos($row['col5'], '와이') !== false)
$item_name = '와이어원단';
}
}
// print_r($item_name);
// 행의 수는 배열의 크기와 동일하므로, count() 함수를 사용하여 구합니다.
$surang = count($eList);
// 행의 수를 출력하거나 활용할 수 있습니다.
// echo "행의 수: " . $surang . "<br>";
// 발주서 수량이 0이면 오류 출력 후 창 닫기
if($surang == 0) {
echo "<script>
alert('정상적인 발주서로 작성된 자료가 없습니다. 데이터가 없습니다.');
window.close(); // 창 닫기
</script>";
exit;
}
// 디코딩된 데이터가 배열인지 확인합니다.
if (!is_array($eList)) {
echo "데이터가 정상적이지 않습니다. 확인바랍니다.";
exit;
}
else {
foreach ($eList as $item) {
$prodcode = $item['col4'];
$items1 = ['KSS01','KSE01','KSS02','KSE02'];
$items2 = ['KWE01'];
// $prodcode가 $items1 배열에 있는 경우
if (in_array($prodcode, $items1)) {
$prodname = '국민방화 스크린 셔터';
}
// $prodcode가 $items2 배열에 있는 경우
elseif (in_array($prodcode, $items2)) {
$prodname = '국민방화 스크린 플러스 셔터';
} else {
$prodname = 'Unknown'; // $prodcode가 어느 배열에도 없는 경우
}
}
}
$indateStr = date("m/d", strtotime($indate));
$todayStr = date("m/d");
?>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/output/mymodal.php'; ?>
<div class="container mt-2">
<div class="d-flex align-items-center justify-content-end mt-1 m-2">
<button type="button" class="btn btn-dark btn-sm mx-3" onclick='location.reload();' title="새로고침"> <i class="bi bi-arrow-clockwise"></i> </button>
<button type="button" class="btn btn-danger btn-sm me-1 ms-1 initialBtn" > <i class="bi bi-trash3-fill"></i> 초기화 </button>
<?php if($QCadmin) { ?>
<button class="btn btn-primary btn-sm me-1 ms-1 approvalBtn" ><i class="bi bi-award-fill"></i> 품질 승인 </button>
<?php } ?>
<button class="btn btn-dark btn-sm me-1 ms-1 saveData" > <i class="bi bi-floppy2-fill"></i> 서버 저장 </button>
<button class="btn btn-dark btn-sm me-1 ms-1" onclick="generatePDF()"> PDF 저장 </button>
<!-- <button class="btn btn-dark btn-sm me-1" onclick="sendmail();"> <i class="bi bi-envelope-arrow-up"></i> 전송 </button> -->
<button class="btn btn-secondary btn-sm me-1 ms-5" onclick="self.close();"> <i class="bi bi-x-lg"></i> 닫기 </button>&nbsp;
</div>
</div>
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data" onkeydown="return captureReturnKey(event)" >
<input type="hidden" id="mode" name="mode" value="<?= isset($mode) ? $mode : '' ?>">
<input type="hidden" id="num" name="num" value="<?= isset($num) ? $num : '' ?>">
<input type="hidden" id="user_name" name="user_name" value="<?= isset($user_name) ? $user_name : '' ?>">
<input type="hidden" id="update_log" name="update_log" value="<?= isset($update_log) ? $update_log : NULL ?>">
<input type="hidden" id="tablename" name="tablename" value="<?= isset($tablename) ? $tablename : '' ?>">
<input type="hidden" id="item_name" name="item_name" value="<?= isset($item_name) ? $item_name : '' ?>">
<input type="hidden" id="recordscreen" name="recordscreen">
<div id="content-to-print">
<br>
<div class="container mt-3">
<div class="d-flex align-items-center justify-content-center m-1">
<table class="table " style="border-collapse: collapse;">
<thead>
<tr>
<th rowspan="3" class="text-center" style="width:70%;">
<div class="row">
<div class="col-sm-2">
<img src="../img/kdlogo.png" alt="경동기업" class="me-1" style="width:100%; height:auto;">
</div>
<div class="col-sm-10">
<div class="d-flex align-items-center justify-content-center m-1">
<span class="text-dark ms-2 me-2 fs-1" > &nbsp; 작 </span>
<span class="text-dark ms-2 me-2 fs-1" > &nbsp; 업 </span>
<span class="text-dark ms-2 me-2 fs-1" > &nbsp; 일 </span>
<span class="text-dark ms-2 fs-1" > &nbsp; 지 </span>
</div>
<br>
<div class="d-flex align-items-center justify-content-center mt-2">
<span class="badge bg-primary ms-2 fs-6" > 스크린 생산부서 </span>
</div>
</div>
</div>
</th>
<th rowspan="3" class="text-center fw-bold" style="height:100px;">결 재</th>
<th class="text-center p-1" style="width : 70px; height:22px; padding:2px;">작성</th>
<th class="text-center p-1" style="width : 70px; height:22px; padding:2px;">검토</th>
<th class="text-center p-1" style="width : 90px; height:22px; padding:2px;">승인</th>
</tr>
<tr style="height:40px;">
<th class="text-center"> <?=$orderman?> <br> <?=$indateStr ?></th>
<th class="text-center">
<div id="reviewDiv" style="display: none;">
<?=$user_name?> <br> <?=$todayStr ?>
</div>
</th>
<th class="text-center">
<div id="approvalDiv" style="display: none;">
<?=$user_name?> <br> <?=$todayStr ?>
</div>
</th>
</tr>
<tr>
<th class="text-center" style="height:22px; padding:2px;">판매/<?=$orderman?></th>
<th class="text-center" style="height:22px; padding:2px;">생산</th>
<th class="text-center text-primary fw-bold" style="height:22px; padding:2px;">품질</th>
</tr>
</thead>
</table>
</div>
<div class="d-flex align-items-center justify-content-center m-1">
<table class="table table-bordered" style="border-collapse: collapse;">
<thead>
<tr>
<th colspan="2" class="text-center align-middle lightgray" style="width:33%;">신 청 업 체</th>
<th colspan="2" class="text-center align-middle lightgray" style="width:33%;">신 청 내 용</th>
</tr>
<tr>
<th class="text-center align-middle lightgray">발주일</th>
<th class="text-center"><?=specialDate($orderdate)?></th>
<th class="text-center align-middle lightgray">현 장 명</th>
<th class="text-center text-primary fw-bold"><?=$outworkplace?> </th>
</tr>
<tr>
<th class="text-center align-middle lightgray">업체명</th>
<th class="text-center"><?=$secondord?> </th>
<th class="text-center align-middle lightgray">작업일자</th>
<th colspan="1" class="text-center text-primary fw-bold"> <span id="workdate"> </span> </th>
</tr>
<tr>
<th class="text-center align-middle lightgray">담당자</th>
<th class="text-center"><?=$orderman?></th>
<th class="text-center align-middle yellowBold">제품 LOT NO</th>
<th class="text-center fw-bold text-primary"><?=$lotNum?></th>
</tr>
<tr>
<th class="text-center align-middle lightgray">연락처</th>
<th class="text-center text-dark fw-bold"><?=$_SESSION['hp']?> </th>
<th class="text-center align-middle lightgray">생산담당자</th>
<th class="text-center">
<button type="button" id="editButton" class="btn btn-primary btn-sm">담당자 입력</button>
<div id="inputContainer" style="display: none;">
<input type="text" id="userNameInput" class="form-control d-inline-block noborder-input text-center" autocomplete="off" style="width: 150px;" value="<?=$user_name?>">
<button type="button" id="cancelButton" class="btn btn-outline-danger btn-sm"> <i class="bi bi-x"> </i> </button>
</div>
</th>
</tr>
<script>
$(document).ready(function() {
// '담당자 입력' 버튼 클릭 시 input 표시 및 버튼 숨김
$('#editButton').on('click', function() {
$('#editButton').hide();
$('#inputContainer').show();
$('#workdate').text('<?php echo $todayStr; ?>');
$('#reviewDiv').show();
});
// '취소' 버튼 클릭 시 원래 상태로 되돌림
$('#cancelButton').on('click', function() {
$('#inputContainer').hide();
$('#reviewDiv').hide();
$('#workdate').text('');
$('#editButton').show();
});
});
</script>
</thead>
</table>
</div>
<!-- 스크린 체크 되어 있으면 스크린 출력 -->
<?php if(isset($slatcheck) && $slatcheck === '1') { ?>
<div class="row justify-content-start m-1 mt-2 ">
■ 작업내역
</div>
<?php
if (is_array($eList) && count($eList) > 0) {
foreach ($eList as $row) {
if($row['col5'] == '실리카') $value = 1220;
else if($row['col5'] == '와이어') $value = 1180;
else if($row['col5'] == '화이바') $value = 1200;
else $value = 1220;
}
}
?>
<div class="d-flex align-items-center justify-content-center m-1">
<table id="mainTable" class="table " style="border-collapse: collapse;">
<tbody>
<tr>
<td rowspan="2" class="text-center align-middle">일련<br>번호</td>
<td rowspan="2" class="text-center align-middle yellowblackBold">입고 LOT NO.</td>
<td rowspan="2" class="text-center align-middle lightgray">제품명</td>
<td rowspan="2" class="text-center align-middle lightgray">부호</td>
<td colspan="2" class="text-center align-middle lightgray">제작사이즈(mm)</td>
<td rowspan="2" class="text-center align-middle lightgray">나머지 <br> 높이</td>
<td colspan="6" class="text-center align-middle lightgray"> 규격(매수) </td>
</tr>
<tr>
<td class="text-center lightgray">가로</td>
<td class="text-center lightgray">세로</td>
<td class="text-center lightgray"> <?=$value?> </td>
<td class="text-center lightgray">900</td>
<td class="text-center lightgray">800</td>
<td class="text-center lightgray">600</td>
<td class="text-center lightgray">400</td>
<td class="text-center lightgray">300</td>
</tr>
<?php
$row_count = 0;
// 합계를 위한 변수 선언 (위쪽)
$totalfirstCut = 0;
$total_900 = 0;
$total_800 = 0; // ← 800 합계 추가
$total_600 = 0;
$total_400 = 0;
$total_300 = 0;
// 데이터가 유효한지 확인
if (is_array($eList) && count($eList) > 0) {
foreach ($eList as $row) {
// 세로 값을 가져옵니다 (col9가 F13에 해당)
$horizontal = isset($row['col10_SW']) ? $row['col10_SW'] : $row['col10']; // 코드 수정 제작사이즈 먼저 확인하고 적용한다.
$vertical = isset($row['col11_SH']) ? $row['col11_SH'] : $row['col11']; // 코드 수정 제작사이즈 먼저 확인하고 적용한다.
$productName = isset($row['col5']) ? $row['col5'] : '';
// 제품명에 따른 절단 치수 결정 ('실리카'는 1220, '와이어'는 1180, '화이바'는 1200)
$result = calculateCutSize($productName, $vertical);
$size_900 = $result['900'];
$size_800 = $result['800'];
$size_600 = $result['600'];
$size_400 = $result['400'];
$size_300 = $result['300'];
// 누적
$totalfirstCut += $result['firstCut'];
$total_900 += $size_900;
$total_800 += $size_800; // ← 800 누적
$total_600 += $size_600;
$total_400 += $size_400;
$total_300 += $size_300;
// 순번, 입고 LOT NO, 제품명, 부호
echo '<td class="text-center" data-bs-toggle="tooltip" data-bs-placement="top" title="전체적용 클릭">' . htmlspecialchars($row['col1']) . '</td>';
echo '<td class="text-center">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control lotnumInput noborder-input text-center" autocomplete="off" name="lotnum[]" placeholder="로트번호"/>
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="top" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div> </div>
</td>';
echo '<td class="text-center ">' . htmlspecialchars($productName) . '</td>';
echo '<td class="text-center ">' . htmlspecialchars($row['col3']) . '</td>';
// 제작 사이즈 가로 및 세로
echo '<td class="text-center yellowredBold fw-bold ">' . htmlspecialchars($horizontal) . '</td>';
echo '<td class="text-center yellowredBold fw-bold ">' . htmlspecialchars($vertical) . '</td>';
// 나머지 높이 출력
echo '<td class="text-center fw-bold ">' . ($result['remaining'] > 0 ? $result['remaining'] : '') . '</td>';
// 각 규격에 따른 수량 계산
echo '<td class="text-center">'. ($result['firstCut'] >0 ? $result['firstCut'] : '') .'</td>';
echo '<td class="text-center">'. ($size_900 >0 ? $size_900 : '') .'</td>';
echo '<td class="text-center">'. ($size_800 >0 ? $size_800 : '') .'</td>'; // ← 800 출력
echo '<td class="text-center">'. ($size_600 >0 ? $size_600 : '') .'</td>';
echo '<td class="text-center">'. ($size_400 >0 ? $size_400 : '') .'</td>';
echo '<td class="text-center">'. ($size_300 >0 ? $size_300 : '') .'</td>';
echo '</tr>';
$row_count++;
}
// 합계 행 출력
echo '<tr>';
echo '<td colspan="7" class="text-center orangeBlackBold">합계</td>';
echo '<td class="text-center orangeBlackBold">'. ($totalfirstCut>0 ? $totalfirstCut : '') .'</td>';
echo '<td class="text-center orangeBlackBold">'. ($total_900 >0 ? $total_900 : '') .'</td>';
echo '<td class="text-center orangeBlackBold">'. ($total_800 >0 ? $total_800 : '') .'</td>'; // ← 800 합계
echo '<td class="text-center orangeBlackBold">'. ($total_600 >0 ? $total_600 : '') .'</td>';
echo '<td class="text-center orangeBlackBold">'. ($total_400 >0 ? $total_400 : '') .'</td>';
echo '<td class="text-center orangeBlackBold">'. ($total_300 >0 ? $total_300 : '') .'</td>';
echo '</tr>';
} else {
echo "<tr><td colspan='12' class='text-center'>데이터가 없습니다.</td></tr>";
}
?>
</tbody>
</table>
</div>
<br>
<div class="d-flex align-items-center justify-content-start m-1 mt-5 mb-5 w-50">
<table class="table " style="border-collapse: collapse; width:35%;">
<tbody>
<tr>
<td class="text-center align-middle yellowblackBold w150px"> 내화실 입고 LOT NO.</td>
<td class="text-center align-middle w150px">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control lotnumInput_wire noborder-input w150px" autocomplete="off" name="wire_lotnum[]" placeholder="로트번호" />
<div class="info-wire-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="top" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<br>
<?php
$row_count = 0;
$total_area = [
1220 => 0,
1180 => 0,
1200 => 0,
'900' => 0,
'800' => 0,
'600' => 0,
'400' => 0,
'300' => 0,
];
if (is_array($eList) && count($eList) > 0) {
foreach ($eList as $row) {
// 가로 길이
$horizontal = isset($row['col10']) ? (int)$row['col10'] : 0;
// 세로 길이
$vertical = isset($row['col11']) ? (int)$row['col11'] : 0;
// 원단 종류 매핑 ('화이버' → '화이바')
$itemSelect = $row['col5'] === '화이버' ? '화이바' : $row['col5'];
// calculateCutSize 호출
$cut = calculateCutSize($itemSelect, $vertical);
// 기준 폭 결정
switch ($itemSelect) {
case '실리카': $width = 1220; break;
case '와이어': $width = 1180; break;
case '화이바': $width = 1200; break;
default: continue 2;
}
// 전체 절단 면적
$total_area[$width] += ($cut['firstCut'] * $width * $horizontal) / 1000000;
// 각 규격별 면적 누적
foreach (['900','800','600','400','300'] as $spec) {
$specSize = (int)$spec;
$total_area[$spec] += ($cut[$spec] * $specSize * $horizontal) / 1000000;
}
}
}
// 전체 면적 합계
$total_sum_area = array_sum($total_area);
// 별도의 테이블로 면적 통계 출력
echo '<div class="d-flex align-items-center justify-content-center m-1">';
echo '<table class="table" style="border-collapse: collapse;">';
echo '<tbody>';
// 1180과 400 라인 출력
echo '<tr>';
echo '<td rowspan="3" class="text-center align-middle lightgray w120px">사용량 (M)</td>';
echo '<td class="text-center blueBlackBold w120px">' . $value . '</td>';
echo '<td class="text-center w120px">' . (round($total_area[$value], 2) > 0 ? round($total_area[$value], 2) : '') . '</td>';
echo '<td class="text-center blueBlackBold w120px">600</td>';
echo '<td class="text-center w120px">' . (round($total_area['600'], 2) > 0 ? round($total_area['600'], 2) : '') . '</td>';
echo '<td rowspan="3" class="text-center align-middle lightgray w120px">사용량 (㎡)</td>';
echo '<td rowspan="3" class="text-center fw-bold w120px">' . (round($total_sum_area, 2) > 0 ? round($total_sum_area, 2) : '') . '</td>';
echo '</tr>';
// 900과 300 라인 출력
echo '<tr>';
echo '<td class="text-center blueBlackBold">900</td>';
echo '<td class="text-center">' . (round($total_area['900'], 2) > 0 ? round($total_area['900'], 2) : '') . '</td>';
echo '<td class="text-center blueBlackBold w120px">400</td>';
echo '<td class="text-center w120px">' . (round($total_area['400'], 2) > 0 ? round($total_area['400'], 2) : '') . '</td>';
echo '</tr>';
// 600 라인 출력
echo '<tr>';
echo '<td class="text-center blueBlackBold">800</td>';
echo '<td class="text-center">' . (round($total_area['800'], 2) > 0 ? round($total_area['800'], 2) : '') . '</td>';
echo '<td class="text-center blueBlackBold">300</td>';
echo '<td class="text-center">' . (round($total_area['300'], 2) > 0 ? round($total_area['300'], 2) : '') . '</td>';
echo '</tr>';
// 사이즈 착오없이 부탁합니다.
echo '<tr>';
echo '<td colspan ="7" class="text-center orangeBlackBold fs-5">';
echo '<div class="d-flex justify-content-center align-items-center >';
echo '<span class="text-primary"> [비 고] </span>';
echo '<input type="text" class="text-center fs-6 noborder-input" id="memo" name="memo" value="사이즈 착오 없이 부탁드립니다.">' ;
echo '</div> </td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '</div>';
?>
</tbody>
</table>
<?php } else { ?>
<div class="row justify-content-center text-danger fs-3 m-1 mt-5 ">
주자재(스크린) 체크 안됨.
</div>
<?php } ?>
</div>
</form>
</div> <!-- end of container -->
<div class="container mb-5 mt-2">
<div class="d-flex align-items-center justify-content-center mb-5">
</div>
</div>
<!-- 페이지로딩 -->
<script>
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
// if(loader)
loader.style.display = 'none';
});
function generatePDF() {
var workplace = '<?php echo $outworkplace; ?>';
var deadline = '<?php echo $indate; ?>';
var deadlineDate = new Date(deadline);
var formattedDate = "(" + String(deadlineDate.getFullYear()).slice(-2) + "." + ("0" + (deadlineDate.getMonth() + 1)).slice(-2) + "." + ("0" + deadlineDate.getDate()).slice(-2) + ")";
var result = 'KD스크린_작업일지(' + workplace +')' + formattedDate + '.pdf';
var element = document.getElementById('content-to-print');
var opt = {
margin: [10, 3, 12, 3], // Top, right, bottom, left margins
filename: result,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 1 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
pagebreak: { mode: [''] }
};
html2pdf().from(element).set(opt).save();
}
// 모달을 호출할 때 tr 요소를 저장하는 변수
var selectedRow;
$(document).on('click', '.lotnumInput', function() {
var row = $(this).closest('tr');
selectedRow = row; // tr 요소 저장
// var itemName = row.find('input[name="item_name[]"]').val(); // 품목명 가져오기
const itemName = $("#item_name").val();
if (itemName) {
$.post('fetch_lot.php', { item_name: itemName })
.done(function(data) {
// alert(data);
$('#lotModal .modal-body').html(data); // 모달 바디에 데이터 로드
setTimeout(function() {
$('#lotModal').modal('show'); // 모달 띄우기
}, 500);
})
.fail(function(xhr, status, error) {
console.error("AJAX Request Failed:", status, error);
console.error("Response:", xhr.responseText);
});
} else {
alert('품목명을 입력해주세요.');
}
});
// 선택한 로트 번호를 적용하는 함수
function selectLotNumber(lotNumber) {
selectedRow.find('input.lotnumInput').val(lotNumber);
selectedRow.find('.info-btn').attr('data-lotnum', lotNumber); // 내부의 .info-btn 선택
$('#lotModal').modal('hide');
}
$(document).on('click', '.nullBtn', function() {
selectLotNumber('');
});
$(document).on('click', '.cancelBtn', function() {
$('#lotModal').modal('hide');
});
$(document).on('click', '.saveData', function() {
saveData();
});
$(document).on('click', '.lotnumInput_wire', function() {
var row = $(this).closest('tr');
selectedRow = row; // tr 요소 저장
// var itemName = row.find('input[name="item_name[]"]').val(); // 품목명 가져오기
var itemName = '내화실';
if (itemName) {
$.post('fetch_lot.php', { item_name: itemName })
.done(function(data) {
// alert(data);
$('#lotModal_wire .modal-body').html(data); // 모달 바디에 데이터 로드
setTimeout(function() {
$('#lotModal_wire').modal('show'); // 모달 띄우기
}, 500);
})
.fail(function(xhr, status, error) {
console.error("AJAX Request Failed:", status, error);
console.error("Response:", xhr.responseText);
});
} else {
alert('품목명을 입력해주세요.');
}
});
// 선택한 로트 번호를 적용하는 함수
function selectLotNumber_wire(lotNumber) {
selectedRow.find('input.lotnumInput_wire').val(lotNumber);
selectedRow.find('.info-wire-btn').attr('data-lotnum', lotNumber); // 내부의 .info-btn 선택
if ($('#lotModal').hasClass('show')) {
$('#lotModal').modal('hide');
}
if ($('#lotModal_wire').hasClass('show')) {
$('#lotModal_wire').modal('hide');
}
}
$(document).on('click', '.nullBtn_wire', function() {
selectLotNumber_wire('');
});
$(document).on('click', '.cancelBtn_wire', function() {
if ($('#lotModal').hasClass('show')) {
$('#lotModal').modal('hide');
}
if ($('#lotModal_wire').hasClass('show')) {
$('#lotModal_wire').modal('hide');
}
});
$(document).on('click', '.lot-done-btn', function() {
const num = $(this).data('num');
const tablename = $(this).data('tablename');
console.log('num', num);
console.log('tablename', tablename);
// SweetAlert2를 사용한 확인 메시지
Swal.fire({
title: '로트 소진 처리',
text: '해당 로트를 소진 처리하시겠습니까?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '예, 처리합니다',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
// 사용자가 '예'를 선택한 경우에만 AJAX 요청 수행
$.ajax({
url: 'update_lotdone.php',
type: 'POST',
data: {
num: num,
tablename: tablename,
mode: 'update',
lotDone: '소진'
},
dataType: 'json',
success: function(response) {
console.log(response);
if (response && response.success) {
Swal.fire({
title: '처리 완료',
text: '소진 처리되었습니다.',
icon: 'success',
confirmButtonText: '확인'
}).then(() => {
// 모달이 존재할 때만 닫기
if ($('#lotModal').hasClass('show')) {
$('#lotModal').modal('hide');
}
if ($('#lotModal_wire').hasClass('show')) {
$('#lotModal_wire').modal('hide');
}
reloadModalContent();
});
} else {
Swal.fire({
title: '오류',
text: '소진 처리 중 오류가 발생했습니다.',
icon: 'error',
confirmButtonText: '확인'
});
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', status, error);
Swal.fire({
title: 'AJAX 오류',
text: '요청 중 오류가 발생했습니다.',
icon: 'error',
confirmButtonText: '확인'
});
}
});
}
});
});
// 모달 내용 새로고침 함수
function reloadModalContent() {
const itemName = $("#item_name").val();
$.post('fetch_lot.php', { item_name: itemName })
.done(function(data) {
$('#lotModal .modal-body').html(data); // 모달의 내용 업데이트
setTimeout(function() {
$('#lotModal').modal('show'); // 모달 다시 표시
}, 500);
})
.fail(function(xhr, status, error) {
console.error("AJAX Request Failed:", status, error);
alert("모달 데이터를 로드하는 중 오류가 발생했습니다.");
});
}
$(document).on('click', '.lot-done-wire-btn', function() {
const num = $(this).data('num');
const tablename = $(this).data('tablename');
console.log('num', num);
console.log('tablename', tablename);
// SweetAlert2를 사용한 확인 메시지
Swal.fire({
title: '로트 소진 처리',
text: '해당 로트를 소진 처리하시겠습니까?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '예, 처리합니다',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
// 사용자가 '예'를 선택한 경우에만 AJAX 요청 수행
$.ajax({
url: 'update_lotdone.php', // 서버에 요청을 보낼 PHP 파일 경로
type: 'POST',
data: {
num: num,
tablename: tablename,
mode: 'update',
lotDone: '소진'
},
dataType: 'json',
success: function(response) {
console.log(response);
if (response && response.success) {
Swal.fire({
title: '처리 완료',
text: '소진 처리되었습니다.',
icon: 'success',
confirmButtonText: '확인'
}).then(() => {
// 성공적으로 처리된 후 모달을 닫고 내용 새로고침
// 모달이 존재할 때만 닫기
if ($('#lotModal').hasClass('show')) {
$('#lotModal').modal('hide');
}
if ($('#lotModal_wire').hasClass('show')) {
$('#lotModal_wire').modal('hide');
}
reloadModalContent_wire();
});
} else {
Swal.fire({
title: '오류',
text: '소진 처리 중 오류가 발생했습니다.',
icon: 'error',
confirmButtonText: '확인'
});
}
},
error: function(xhr, status, error) {
console.error('AJAX Error:', status, error);
Swal.fire({
title: 'AJAX 오류',
text: '요청 중 오류가 발생했습니다.',
icon: 'error',
confirmButtonText: '확인'
});
}
});
}
});
});
// 모달 내용 새로고침 함수
function reloadModalContent_wire() {
const itemName = '내화실'; // 예시로 사용한 품목명, 필요시 다른 값으로 변경
$.post('fetch_lot.php', { item_name: itemName })
.done(function(data) {
$('#lotModal_wire .modal-body').html(data); // 모달의 내용 업데이트
setTimeout(function() {
$('#lotModal_wire').modal('show'); // 모달 다시 표시
}, 500);
})
.fail(function(xhr, status, error) {
console.error("AJAX Request Failed:", status, error);
alert("모달 데이터를 로드하는 중 오류가 발생했습니다.");
});
}
$(document).on('click', '.approvalBtn', function() {
// 승인자의 이름과 오늘 날짜 가져오기
const userName = '<?=$user_name?>'; // PHP로부터 가져온 사용자 이름
const todayStr = '<?=$todayStr?>'; // PHP로부터 가져온 오늘 날짜
// 승인 정보를 approvalDiv에 표시
$('#approvalDiv').html(
userName + '<br>' + todayStr +
' <i class="bi bi-x-circle remove-approval" style="cursor: pointer;"></i>'
);
$('#approvalDiv').show();
// 결재 정보를 업데이트하여 저장 로직에 반영
updateApprovalData(userName, todayStr);
saveData();
});
// 결재 정보 업데이트 함수
function updateApprovalData(userName, date) {
// 저장 로직을 위해 결재 정보 업데이트
let approvalData = {
writer: {
name: $('#orderman').text().trim(),
date: '<?=$indateStr?>'
},
reviewer: {
name: $('#reviewDiv').is(':visible') ? '<?=$user_name?>' : '',
date: '<?=$todayStr?>'
},
approver: {
name: userName,
date: date
}
};
// 저장할 JSON 데이터 업데이트
let formData = JSON.parse($('#recordscreen').val() || '[]');
const approvalIndex = formData.findIndex(item => item.approval);
if (approvalIndex !== -1) {
formData[approvalIndex].approval = approvalData;
} else {
formData.push({ approval: approvalData });
}
// JSON 문자열로 다시 저장
$('#recordscreen').val(JSON.stringify(formData));
}
// 결재 취소 기능
$(document).on('click', '.remove-approval', function() {
// 결재 정보를 지우고 화면에서 숨김
$('#approvalDiv').html('').hide();
// JSON 데이터에서 결재자의 정보 제거
let formData = JSON.parse($('#recordscreen').val() || '[]');
const approvalIndex = formData.findIndex(item => item.approval);
if (approvalIndex !== -1) {
formData[approvalIndex].approval.approver.name = '';
formData[approvalIndex].approval.approver.date = '';
}
// JSON 문자열로 다시 저장
$('#recordscreen').val(JSON.stringify(formData));
Toastify({
text: "결재 정보가 삭제되었습니다.",
duration: 2000,
close: true,
gravity: "top",
position: "center",
style: {
background: "linear-gradient(to right, #ff5f6d, #ffc371)"
},
}).showToast();
saveData();
});
function captureReturnKey(e) {
if(e.keyCode==13 && e.srcElement.type != 'textarea')
return false;
}
function recaptureReturnKey(e) {
if(e.keyCode==13 && e.srcElement.type != 'textarea')
return false;
}
// 삽입/수정하는 모듈
function saveData() {
// json 형태로 form문에 저장하기
let formData = [];
// 결재 부분 정보 저장
let approvalData = {
writer: {
name: $('#orderman').text().trim(),
date: '<?=$indateStr?>'
},
reviewer: {
name: $('#reviewDiv').is(':visible') ? '<?=$user_name?>' : '',
date: '<?=$todayStr?>'
},
approver: {
name: $('#approvalDiv').is(':visible') ? '<?=$user_name?>' : '',
date: '<?=$todayStr?>'
}
};
formData.push({ approval: approvalData });
// 생산담당자 정보 저장
let productionManager = $('#userNameInput').val();
formData.push({ productionManager: productionManager });
// 입고 LOT NO 정보 저장 (행별)
let lotNums = [];
$('.lotnumInput').each(function() {
lotNums.push($(this).val());
});
formData.push({ lotNumbers: lotNums });
// 내화실 입고 LOT NO 정보 저장
let wireLotNums = [];
$('.lotnumInput_wire').each(function() {
wireLotNums.push($(this).val());
});
formData.push({ wireLotNumbers: wireLotNums });
// 추가 정보 저장
formData.push({ num: $('#num').val() });
formData.push({ tablename: $('#tablename').val() });
formData.push({ update_log: $('#update_log').val() });
formData.push({ memo: $('#memo').val() });
// JSON 문자열로 변환
let jsonString = JSON.stringify(formData);
// 숨겨진 필드에 JSON 데이터 설정
$('#recordscreen').val(jsonString);
$("#overlay").show(); // 오버레이 표시
$("button").prop("disabled", true); // 모든 버튼 비활성화
showMsgModal(2); // 파일저장중
// 폼데이터 전송시 사용함 Get form
var form = $('#board_form')[0];
var datasource = new FormData(form);
$.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
url: "insert_recordscreen.php",
type: "post",
data: datasource,
dataType: "json",
success: function(data) {
console.log(data);
setTimeout(function() {
Toastify({
text: "저장완료",
duration: 3000,
close: true,
gravity: "top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
setTimeout(function() {
hideMsgModal();
$("#overlay").hide(); // 오버레이 숨김
}, 1000);
}, 1000);
},
error: function(jqxhr, status, error) {
console.log(jqxhr, status, error);
alert("An error occurred: " + error);
}
});
}
// 초기값 불러오기
$(document).ready(function() {
if (recordscreenData.length > 0) {
// 결재 부분 정보
const approval = recordscreenData.find(item => item.approval);
if (approval) {
$('#orderman').text(approval.approval.writer.name || '');
$('#indateStr').text(approval.approval.writer.date || '');
$('#reviewDiv').show();
$('#reviewDiv').html(approval.approval.reviewer.name + '<br>' + approval.approval.reviewer.date);
// 승인 정보가 있을 때만 승인 정보를 표시하고 x 마크를 추가
if (approval.approval.approver.name && approval.approval.approver.date) {
$('#approvalDiv').show();
$('#approvalDiv').html(
approval.approval.approver.name + '<br>' + approval.approval.approver.date +
' <i class="bi bi-x-circle remove-approval" style="cursor: pointer;"></i>'
);
} else {
// 승인 정보가 없을 때는 공백으로 처리
$('#approvalDiv').hide().html('');
}
$('#workdate').text(approval.approval.writer.date);
}
// 생산담당자 정보
const productionManager = recordscreenData.find(item => item.productionManager);
if (productionManager && productionManager.productionManager) {
$('#userNameInput').val(productionManager.productionManager).show();
$('#inputContainer').show(); // input 필드 컨테이너 표시
$('#editButton').hide(); // '생산자 입력' 버튼 숨김
} else {
$('#userNameInput').val('');
$('#inputContainer').hide();
$('#editButton').show();
}
// 입고 LOT NO 정보
const lotNumbers = recordscreenData.find(item => item.lotNumbers);
if (lotNumbers) {
$('.lotnumInput').each(function(index) {
$(this).val(lotNumbers.lotNumbers[index] || '');
});
$('.info-btn').each(function(index) {
$(this).attr('data-lotnum', lotNumbers.lotNumbers[index] || '');
});
}
// 내화실 입고 LOT NO 정보
const wireLotNumbers = recordscreenData.find(item => item.wireLotNumbers);
if (wireLotNumbers) {
$('.lotnumInput_wire').each(function(index) {
$(this).val(wireLotNumbers.wireLotNumbers[index] || '');
});
$('.info-wire-btn').each(function(index) {
$(this).attr('data-lotnum', wireLotNumbers.wireLotNumbers[index] || '');
});
}
// 업데이트 로그가 있을 경우 표시
const updateLog = recordscreenData.find(item => item.update_log);
if (updateLog) {
$('#update_log').val(updateLog.update_log || '');
}
// 메모가 있을 경우
const memo = recordscreenData.find(item => item.memo);
if (memo) {
$('#memo').val(memo.memo || '사이즈 착오없이 부탁드립니다.');
}
}
});
// 첫번째 요소를 클릭하면 전체 로트번호 적용하기
$(document).ready(function() {
// id가 mainTable인 테이블의 첫 번째 td를 클릭했을 때 이벤트를 등록합니다.
$('#mainTable').on('click', 'td:first-child', function() {
// 클릭한 첫 번째 td의 형제인 두 번째 td 요소의 값을 가져옵니다.
var secondTdValue = $(this).siblings().find('input').val();
// id가 mainTable인 테이블에서 두 번째 td 요소에 해당 값을 적용합니다.
$('#mainTable tbody tr').each(function() {
$(this).find('td:nth-child(2) input').val(secondTdValue);
});
});
});
// 부트스트랩 툴팁
$(document).ready(function() {
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
});
$(document).ready(function() {
// 초기화 버튼 클릭 이벤트
$('.initialBtn').on('click', function() {
// 초기화 확인 알림
Swal.fire({
title: '초기화',
text: "모든 데이터를 초기화하시겠습니까?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '예, 초기화합니다',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
// recordscreen 값을 빈 배열로 초기화
const initialData = JSON.stringify([]); // 빈 배열로 초기화
// recordscreen hidden input에 초기화된 데이터 설정
$('#recordscreen').val(initialData);
// 초기화된 데이터 저장 요청
$.ajax({
url: "insert_recordscreen.php",
type: 'POST',
data: {
num: $('#num').val() ,
tablename: $('#tablename').val() ,
update_log: $('#update_log').val() ,
recordscreen: initialData },
success: function(response) {
Swal.fire({
title: '초기화 완료',
text: "모든 데이터가 초기화되었습니다.",
icon: 'success',
confirmButtonText: '확인'
}).then(() => {
saveAndClose();
// 페이지 새로고침
location.reload();
});
},
error: function(jqxhr, status, error) {
Swal.fire({
title: '오류',
text: "초기화 중 오류가 발생했습니다.",
icon: 'error',
confirmButtonText: '확인'
});
console.log("AJAX Error: ", status, error);
}
});
}
});
});
});
// 팝업 창에서 데이터 저장 및 닫기 함수
function saveAndClose() {
// const updatedData = {
// // rawLot: $("#rawLot").val(),
// // fabric_lot: $("#fabric_lot").val(),
// // lot_number: $("#lot_number").val(),
// resultJudgement: $("#resultJudgement").val(),
// // reg_date: $("#reg_date").val(),
// // prodDisplay: $("#prod").val(),
// // specDisplay: $("#spec").val(),
// // slengthDisplay: $("#slength").val(),
// // surang: $("#surang").val(),
// // author: $("#author").val(),
// // remark: $("#remark").val()
// };
// // 부모 창에 데이터 업데이트 호출
// window.opener.closePopupAndUpdateRow(updatedData);
// 팝업 창 닫기
// window.close();
}
ajaxRequest1 = null;
$(document).ready(function () {
$(document).on('click', '.info-btn, .info-wire-btn', function () {
var lotnum = $(this).data('lotnum');
console.log('lotnum :', lotnum);
if (!lotnum) {
Swal.fire('알림', '로트번호를 입력하세요.', 'warning');
return;
}
// AJAX 요청을 통해 데이터 가져오기
if (ajaxRequest1 !== null) {
ajaxRequest1.abort();
}
ajaxRequest1 = $.ajax({
url: 'fetch_certificate.php', // 성적서를 가져오는 서버 파일
type: 'POST',
data: { lotnum: lotnum },
dataType: 'json',
success: function (response) {
console.log(response);
if (response.success) {
// 성적서 데이터를 화면에 표시
// $('#certificateModal .modal-body').html(response.data);
// $('#certificateModal').modal('show');
var num = response.num;
var itemname = response.itemname;
var spec = response.specification;
var remarks = response.remarks;
// 클릭 이벤트 전파 방지
event.stopPropagation();
// viewBoardInstock 함수 호출
viewBoardInstock(num, itemname, spec, remarks);
} else {
Swal.fire('오류', '성적서를 가져올 수 없습니다.', 'error');
}
ajaxRequest1 = null;
},
error: function (jqXHR, textStatus, errorThrown) {
console.error('AJAX Error:', textStatus, errorThrown);
console.error('Response Text:', jqXHR.responseText);
Swal.fire('오류', '서버 요청에 실패했습니다. <br> ' + textStatus + ': ' + errorThrown, 'error');
},
});
});
});
</script>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/instock/common/viewJS.php'; ?> <!--공통 JS -->
</body>
</html>