Files
sam-kd/output/viewOutput_slat.php

1379 lines
54 KiB
PHP
Raw Permalink Normal View History

<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
$title_message = '철재스라트 출고증';
$tablename = 'output';
$item ='출고증';
$emailTitle ='출고증';
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
// 출고담당자관리자 명단
$QCadmin = false ;
if($user_name=='이세희' || $user_name=='개발자' || $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'] : '';
require_once($_SERVER['DOCUMENT_ROOT'] . "/estimate/fetch_unitprice.php");
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($estimateSlatList, true);
// 행의 수는 배열의 크기와 동일하므로, count() 함수를 사용하여 구합니다.
$surang = count($eList);
// COD 출고증 certificate of delivery
$COD = isset($COD) ? json_decode($COD, true) : [];
// print_r($COD);
// JSON 데이터를 JavaScript 변수로 변환
echo "<script>";
echo "var CODData = " . json_encode($COD) . ";";
echo "</script>";
// echo '<pre>';
// print_r($eList);
// echo '</pre>';
// 행의 수는 배열의 크기와 동일하므로, count() 함수를 사용하여 구합니다.
$surang = count($eList);
// 행의 수를 출력하거나 활용할 수 있습니다.
// echo "행의 수: " . $surang . "<br>";
$THscreenSu = $surang + 2 ;
// 디코딩된 데이터가 배열인지 확인합니다.
if (!is_array($eList)) {
echo "데이터가 정상적이지 않습니다. 확인바랍니다.";
exit;
}
else {
foreach ($eList as $item) {
$prodcode = $item['col4'];
$items1 = ['KQTS01'];
$items2 = ['KTE01'];
// $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");
$rowCounter = 1; // 아이템 행 카운터 초기값 1
?>
<div class="container mt-2">
<div class="d-flex align-items-center justify-content-end mt-1 m-2">
<div class="d-flex align-items-center">
<span class="me-5">(<?php echo isset($warranty) && $warranty === '인정' ? '인정' : ''; ?><?php echo isset($slatcheck) && $slatcheck === '1' ? ', 스크린' : ''; ?><?php echo isset($motor) && $motor === '1' ? ', 모터' : ''; ?><?php echo isset($steel) && $steel === '1' ? ', 절곡' : ''; ?><?php echo isset($partscheck) && $partscheck === '1' ? ', 부자재' : ''; ?>)</span>
</div>
<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-dark btn-sm me-1 ms-1 saveData" > <i class="bi bi-floppy2-fill"></i> 서버 저장 </button>
<button type="button" class="btn btn-dark btn-sm me-1" onclick="generatePDF()"> PDF 저장 </button>
<button type="button" class="btn btn-dark btn-sm me-1" onclick="sendmail();"> <i class="bi bi-envelope-arrow-up"></i> 전송 </button>
<button type="button" class="btn btn-secondary btn-sm ms-5" onclick="self.close();"> <i class="bi bi-x-lg"></i> 닫기 </button>&nbsp;
</div>
</div>
<div class="modal fade" id="lotModal" tabindex="-1" aria-labelledby="lotModalLabel" aria-hidden="true">
<div class="modal-dialog modal-full">
<div class="modal-content" style="width:750px;">
<div class="modal-header">
<h5 class="modal-title" id="lotModalLabel">출고증 로트번호 선택</h5>
<button type="button" class="btn-close cancelBtn" aria-label="Close"></button>
</div>
<div class="modal-body">
<ul class="nav nav-tabs" id="lotTabs" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link" id="material-tab" data-bs-toggle="tab" data-bs-target="#material" type="button" role="tab" aria-controls="material" aria-selected="false">로트 찾기</button>
</li>
</ul>
<div class="tab-content" id="lotTabContent">
<div class="tab-pane fade show active" id="material" role="tabpanel" aria-labelledby="material-tab">
<!-- 원자재 로트번호 목록 -->
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm nullBtn_bending">공백 삽입</button>
<button type="button" class="btn btn-secondary btn-sm cancelBtn">취소</button>
</div>
</div>
</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="COD" name="COD"> <!-- COD는 출고증 로트번호 기록위한 변수임 -->
<div id="content-to-print">
<br>
<div class="container mt-3">
<div class="row mt-2">
<div class="d-flex align-items-center justify-content-start">
<table class="table avoid-break " style="border-collapse: collapse;">
<thead>
<tr>
<th colspan="5" rowspan="4" 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 fs-1" > &nbsp; </span>
</div>
<br>
<div class="d-flex align-items-center justify-content-center mt-2">
<span class="text-dark ms-2 " style="font-size:10px;" > 전화 : 031-983-5130 | 팩스 : 02-6911-6315 | 이메일 : kd5130@naver.com </span>
</div>
</div>
</div>
</th>
<th class="text-center " style="width:5%;">로트번호</th>
<th colspan="3" class="text-center text-primary fw-bold" style="width:30%; "> <?=$lotNum?> </th>
</tr>
<tr>
<th rowspan="3" class="text-center fw-bold" style="height:100px;"> </th>
<th class="text-center p-1 clickable" style="width : 70px; height:22px; padding:2px; cursor:pointer;" id="writer">작성</th>
<th class="text-center p-1 clickable" style="width : 70px; height:22px; padding:2px; cursor:pointer;" id="reviewer">검토</th>
<th class="text-center p-1 clickable approval-only" style="width : 90px; height:22px; padding:2px; cursor:pointer;" id="approver">승인</th>
</tr>
<tr style="height:40px;">
<th class="text-center" id="writerDisplay"></th>
<th class="text-center" id="reviewerDisplay"></th>
<th class="text-center" id="approvalDisplay"></th>
</tr>
<tr>
<th class="text-center" style="height:22px; padding:2px;">판매/<?=$orderman?></th>
<th class="text-center" style="height:22px; padding:2px;"><span class="text-primary"> 출하 </span></th>
<th class="text-center" style="height:22px; padding:2px;">생산관리</th>
</tr>
<tr>
<th class="text-center blueBlackBold" > </th>
<th class="text-center blueBlackBold"><?=$prodname?></th>
<th class="text-center blueBlackBold">제품명</th>
<th class="text-center blueBlackBold"><?=$prodcode?></th>
<th class="text-center blueBlackBold">인정번호</th>
<th colspan="4" class="text-center blueBlackBold fw-bold"><?=$warrantyNum?></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row mt-2">
<div class="d-flex align-items-center justify-content-start">
<table class="table avoid-break" 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>
<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 colspan="3" 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"><?=specialDate($outdateplusone)?> </th>
<th class="text-center align-middle lightgray">인수담당자</th>
<th colspan="1" class="text-center text-primary fw-bold"><?=$receiver?> </th>
</tr>
<tr>
<th class="text-center align-middle lightgray">발주 담당자</th>
<th class="text-center"><?=$receiver?></th>
<th class="text-center align-middle lightgray">출고일</th>
<th colspan="1" class="text-center text-primary fw-bold"><?=specialDate($outdate)?> </th>
<th class="text-center align-middle lightgray">인수자연락처</th>
<th class="text-center text-primary fw-bold"><?=$phone?> </th>
</tr>
<tr>
<th class="text-center align-middle lightgray">담당자 연락처</th>
<th class="text-center text-dark fw-bold"><?=$phone?> </th>
<th class="text-center align-middle lightgray">셔터총수량</th>
<th class="text-center"> <?=$surang ?> (개소) </th>
<th class="text-center align-middle lightgray"> </th>
<th class="text-center"> <?=$delivery ?> </th>
</tr>
<tr>
<th class="text-center align-middle lightgray">배송지 주소</th>
<th colspan="5" class="text-center"><?=$outputplace?></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="d-flex align-items-center justify-content-start ">
<table class="table" style="border-collapse: collapse; padding:5;">
<tbody>
<tr>
<td class="text-center fw-bold w120px" >
* 별도 추가사항
</td>
<td class="text-center fw-bold fs-6" style="background-color:yellow; padding:15!important;" >
<?=$displayText?>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 부자재 체크 되어 있으면 부자재 출력 -->
<?php if(isset($partscheck) && $partscheck === '1') { ?>
<div class="row mt-2">
<div class="d-flex justify-content-start">
<?php echo $rowCounter . '. 부자재 - 감기샤프트, 각파이프, 앵글, 마환봉 '; ?>
</div>
</div>
<!-- 감기샤프트 로트번호 부여-->
<?php
if (True) {
// 감기샤프트 데이터에 품목 번호와 수량을 함께 저장
$shaft_data = [
'4인치_3000' => ['item_code' => '감기샤프트-114.3*2T,L:3,000', 'quantity' => 0],
'4인치_4500' => ['item_code' => '감기샤프트-114.3*2T,L:4,500', 'quantity' => 0],
'4인치_6000' => ['item_code' => '감기샤프트-114.3*2T,L:6,000', 'quantity' => 0],
'5인치_6000' => ['item_code' => '감기샤프트-139.8*2.9T,L:6,000', 'quantity' => 0],
'5인치_7000' => ['item_code' => '감기샤프트-139.8*2.9T,L:7,000', 'quantity' => 0],
'5인치_8200' => ['item_code' => '감기샤프트-139.8*2.9T,L:8,200', 'quantity' => 0],
'6인치_3000' => ['item_code' => '감기샤프트-165.2*2.9T,L:3,000', 'quantity' => 0],
'6인치_6000' => ['item_code' => '감기샤프트-165.2*2.9T,L:6,000', 'quantity' => 0],
'6인치_7000' => ['item_code' => '감기샤프트-165.2*2.9T,L:7,000', 'quantity' => 0],
'6인치_8000' => ['item_code' => '감기샤프트-165.2*2.9T,L:8,000', 'quantity' => 0],
'8인치_8200' => ['item_code' => '감기샤프트-216.3*3.2T,L:8,200', 'quantity' => 0],
];
// 부속자재 데이터에 품목 번호와 수량을 함께 저장
$subs_data = [
'각파이프-3000' => ['item_code' => '각파이프-50*30*1.4T,L:3,000', 'quantity' => 0],
'각파이프-6000' => ['item_code' => '각파이프-50*30*1.4T,L:6,000', 'quantity' => 0],
'조인트바-300' => ['item_code' => '조인트바-25*4.5T,L:300', 'quantity' => 0],
'앵글-2500' => ['item_code' => '앵글-50*50*4T,L:2,500', 'quantity' => 0],
];
// 받침용앵글 데이터 초기화
$angle_data = [
'받침용앵글-380' => ['item_code' => '받침용앵글-50*50*3T,L:380', 'quantity' => 0],
'받침용앵글-530' => ['item_code' => '받침용앵글-50*50*4T,L:530', 'quantity' => 0],
'받침용앵글-600' => ['item_code' => '받침용앵글-50*50*4T,L:600', 'quantity' => 0],
'받침용앵글-690' => ['item_code' => '받침용앵글-50*50*4T,L:690', 'quantity' => 0],
];
// 받침용앵글 수량 누적 계산
foreach ($bracketData as $bracket) {
if (isset($bracket['size'], $bracket['quantity'])) {
// `size`에서 앞 숫자 추출
preg_match('/^\d+/', $bracket['size'], $matches);
$size = $matches[0] ?? null;
// 크기에 따라 데이터 누적
if ($size && isset($angle_data["받침용앵글-$size"])) {
$angle_data["받침용앵글-$size"]['quantity'] += intval($bracket['quantity']);
}
}
}
// 데이터를 누적하여 합산 (스크린과 철재스라트의 col번호 다름 주의)
foreach ($eList as $item) {
$shaft_data['4인치_3000']['quantity'] += intval($item['col61']);
$shaft_data['4인치_4500']['quantity'] += intval($item['col62']);
$shaft_data['4인치_6000']['quantity'] += intval($item['col63']);
$shaft_data['5인치_6000']['quantity'] += intval($item['col64']);
$shaft_data['5인치_7000']['quantity'] += intval($item['col65']);
$shaft_data['5인치_8200']['quantity'] += intval($item['col66']);
$shaft_data['6인치_3000']['quantity'] += intval($item['col67']);
$shaft_data['6인치_6000']['quantity'] += intval($item['col68']);
$shaft_data['6인치_7000']['quantity'] += intval($item['col69']);
$shaft_data['6인치_8000']['quantity'] += intval($item['col70']);
$shaft_data['8인치_8200']['quantity'] += intval($item['col71']);
// 부속자재 누적
$subs_data['각파이프-3000']['quantity'] += intval($item['col74']);
$subs_data['각파이프-6000']['quantity'] += intval($item['col75']);
$subs_data['조인트바-300']['quantity'] += intval($item['col76']);
$subs_data['앵글-2500']['quantity'] += intval($item['col77']);
}
// print_r($subs_data);
// 받침용앵글 규격
$bracketAngle = $item['col23'];
// HTML 구조 시작
echo '<div class="row">';
// 감기샤프트 부분
echo '<div class="col-sm-6 justify-content-start">';
echo '<table class="table avoid-break" style="border-collapse: collapse;">';
echo '<thead>';
echo '<tr><th colspan="3" class="text-center lightgray">감기샤프트</th></tr>';
echo '<tr>';
echo '<th class="text-center lightgray">규격</th>';
echo '<th class="text-center lightgray">수량</th>';
echo '<th class="text-center yellowblackBold">입고 LOT NO.</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
// 감기샤프트 데이터 출력
foreach ($shaft_data as $label => $data) {
if ($data['quantity'] > 0) {
echo '<tr>';
echo '<td class="text-center blueBold">' . str_replace('_', ' ', $label) . '</td>';
echo '<td class="text-center fw-bold">' . $data['quantity'] . '</td>';
echo '<td class="text-center w160px yellowblackBold">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control noborder-input lotnumInput" autocomplete="off" placeholder="로트번호" data-itemname="' . $data['item_code'] . '" data-usesurang="' . $data['quantity'] . '" name="lotnum_side[]" />
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="left" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>';
echo '</tr>';
}
}
echo '</tbody>';
echo '</table>';
echo '</div>'; // 감기샤프트 부분 끝
// 부속자재 부분
echo '<div class="col-sm-6 ">';
echo '<table class="table avoid-break" style="border-collapse: collapse;">';
echo '<thead>';
echo '<tr><th colspan="4" class="text-center lightgray">부속자재</th></tr>';
echo '<tr>';
echo '<th class="text-center lightgray">규격</th>';
echo '<th class="text-center lightgray">길이</th>';
echo '<th class="text-center lightgray">수량</th>';
echo '<th class="text-center yellowblackBold">입고 LOT NO.</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
// 각파이프 데이터 출력
$pipe_rowspan = 0;
if ($subs_data['각파이프-3000']['quantity'] > 0) {
$pipe_rowspan++;
}
if ($subs_data['각파이프-6000']['quantity'] > 0) {
$pipe_rowspan++;
}
if ($pipe_rowspan > 0) {
echo '<tr>';
echo '<td class="text-center blueBold" rowspan="' . $pipe_rowspan . '">각파이프</td>';
if ($subs_data['각파이프-3000']['quantity'] > 0) {
echo '<td class="text-center fw-bold">3000</td>';
echo '<td class="text-center fw-bold">' . $subs_data['각파이프-3000']['quantity'] . '</td>';
echo '<td class="text-center w160px yellowblackBold">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control noborder-input lotnumInput" autocomplete="off" placeholder="로트번호" data-itemname="' . $subs_data['각파이프-3000']['item_code'] . '" data-usesurang="' . $subs_data['각파이프-3000']['quantity'] . '" name="lotnum_side[]" />
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="left" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>';
echo '</tr>';
}
if ($subs_data['각파이프-6000']['quantity'] > 0) {
echo '<td class="text-center fw-bold">6000</td>';
echo '<td class="text-center fw-bold">' . $subs_data['각파이프-6000']['quantity'] . '</td>';
echo '<td class="text-center w160px yellowblackBold">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control noborder-input lotnumInput" autocomplete="off" placeholder="로트번호" data-itemname="' . $subs_data['각파이프-6000']['item_code'] . '" data-usesurang="' . $subs_data['각파이프-6000']['quantity'] . '" name="lotnum_side[]" />
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="left" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>';
echo '</tr>';
}
}
// 앵글
if ($subs_data['앵글-2500']['quantity'] > 0) {
echo '<tr>';
echo '<td class="text-center blueBold">앵글<br>(40*40*3T)</td>';
echo '<td class="text-center fw-bold">2500</td>';
echo '<td class="text-center fw-bold">' . $subs_data['앵글-2500']['quantity'] . '</td>';
echo '<td class="text-center w160px yellowblackBold">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control noborder-input lotnumInput" autocomplete="off" placeholder="로트번호" data-itemname="' . $subs_data['앵글-2500']['item_code'] . '" data-usesurang="' . $subs_data['앵글-2500']['quantity'] . '" name="lotnum_side[]" />
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="left" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>';
echo '</tr>';
}
// 받침용앵글 데이터 출력
foreach ($angle_data as $label => $data) {
if ($data['quantity'] > 0) {
echo '<tr>';
echo '<td class="text-center blueBold" colspan="2">' . $data['item_code'] . '</td>';
echo '<td class="text-center fw-bold">' . $data['quantity'] . '</td>';
echo '<td class="text-center w160px yellowblackBold">';
echo ' <div class="d-flex justify-content-center align-items-center">';
echo ' <input type="text" class="form-control noborder-input lotnumInput" autocomplete="off" placeholder="로트번호"';
echo ' data-itemname="' . $data['item_code'] . '"';
echo ' data-usesurang="' . $data['quantity'] . '" name="lotnum_side[]" />';
echo ' <div class="info-btn" data-lotnum="" data-bs-toggle="tooltip"';
echo ' data-bs-placement="left" title="성적서">';
echo ' <i class="bi bi-info-circle-fill"></i>';
echo ' </div>';
echo ' </div>';
echo '</td>';
echo '</tr>';
}
}
echo '</tbody>';
echo '</table>';
echo '</div>'; // 부속자재 부분 끝
echo '</div>'; // row 끝
}
$rowCounter++; } // end of partscheck 체크박스 ?>
<!-- 모터 체크 되어 있으면 모터 출력 -->
<?php if(isset($motor) && $motor === '1') { ?>
<div class="row mt-2">
<div class="d-flex align-items-center justify-content-start">
2. 모터
</div>
<?php
// 모터 부분
if (True) {
$specifications = calculateMotorSpecifications_slat($eList);
$bracketSpec = calculateBracket_slat($eList);
$bracketAngleSpec = calculateBracketAngle_slat($eList);
// 모터 관련 데이터
$columns = [
$specifications['col1_sum'],
$specifications['col2_sum'],
$specifications['col3_sum'],
$specifications['col4_sum'],
$specifications['col5_sum'],
$specifications['col6_sum'],
$specifications['col7_sum']
];
// 연동제어기 관련 데이터
$other_columns = [
$specifications['col8_sum'],
$specifications['col9_sum'],
$specifications['col10_sum'],
];
$volt = isset($eList[0]['col19']) ? $eList[0]['col19'] : '';
$wireless = isset($eList[0]['col19_wireless']) ? $eList[0]['col19_wireless'] : '';
// HTML 구조 시작
echo '<div class="row ">';
// 1) 모터 부분
echo '<div class="col-sm-4 justify-content-center">';
echo '<table class="table avoid-break" style="border-collapse: collapse;">';
echo '<thead>';
echo '<tr><th colspan="3" class="text-center lightgray">모터종류(KG) ,전원: ' . $volt . '(' . $wireless . ') </th></tr>';
echo '<tr>';
echo '<th class="text-center lightgray">용량</th>';
echo '<th class="text-center lightgray">수량</th>';
echo '<th class="text-center yellowblackBold "> 입고 LOT NO.</th>';
echo '<tr>';
echo '</thead>';
echo '<tbody>';
$motor_labels = ['150KG', '300KG', '400KG', '500KG', '600KG', '800KG', '1000KG'];
$innercounter = 0;
for ($i = 0; $i < count($columns); $i++) {
if ($columns[$i] !== null && $columns[$i] !== 0) {
echo '<tr>';
echo '<td class="text-center">' . $motor_labels[$i] . '</td>';
echo '<td class="text-center">' . $columns[$i] . '</td>';
// 모터 코드 생성
$code = '전동개폐기-' . $motor_labels[$i] . $volt . '(' . $wireless . ')'; // 규격 생성
// motor-lot 필드에 data-index 추가
echo '<td class="text-center w160px yellowblackBold">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control noborder-input lotnumInput motor-lot" autocomplete="off" placeholder="로트번호" data-itemname="'. $code . '" data-usesurang="" name="motor_lot[]" data-index="' . $innercounter . '" />
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="left" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>';
echo '</tr>';
$innercounter ++;
}
}
echo '</tbody>';
echo '</table>';
echo '</div>'; // 모터 부분 끝
// 2) 브라켓트 부분
echo '<div class="col-sm-4 d-flex align-items-top justify-content-center">';
echo '<table class="table" style="border-collapse: collapse;">';
echo '<thead>';
echo '<tr><th colspan="3" class="text-center lightgray">브라켓트 </th></tr>';
echo '<tr>';
echo '<th class="text-center lightgray">크기</th>';
echo '<th class="text-center lightgray">수량</th>';
echo '<th class="text-center yellowblackBold "> 입고 LOT NO.</th>';
echo '<tr>';
echo '</thead>';
echo '<tbody>';
// 브라켓과 앵글 데이터를 배열에 저장
$bracketData = array_values($bracketSpec['bracketSizes']); // 키를 숫자 인덱스로 변환
$angleData = array_values($bracketAngleSpec['bracketAngleSizes']); // 키를 숫자 인덱스로 변환
// 두 배열의 최대 길이를 구함
$maxRows = max(count($bracketData), count($angleData));
// 브라켓 부분에서도 같은 인덱스를 사용하여 data-index 속성을 추가
$innercounter = 0;
for ($i = 0; $i < $maxRows; $i++) {
echo '<tr>';
if (isset($bracketData[$i])) {
echo '<td class="text-center">' . $bracketData[$i]['size'] . '</td>';
echo '<td class="text-center">' . $bracketData[$i]['quantity'] . '</td>';
$size = $bracketData[$i]['size']; // '380*200'
$sizeParts = explode('*', $size); // '380'과 '200'으로 분리
$code = '베어링부-' . $sizeParts[0] . 'B'; // '380B'로 변환
echo '<td class="text-center w160px yellowblackBold">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control noborder-input lotnumInput bracket-lot" autocomplete="off" placeholder="로트번호" data-itemname="' . $code . '" data-usesurang="" name="bracket_lot[]" data-index="' . $innercounter . '" />
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="left" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>';
$innercounter++ ;
} else {
echo '<td class="text-center">-</td>';
echo '<td class="text-center">-</td>';
echo '<td class="text-center">-</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>'; // 브라켓트 부분 끝
// 3) 연동제어기 부분
echo '<div class="col-sm-4 d-flex align-items-top justify-content-center">';
echo '<table class="table avoid-break" style="border-collapse: collapse;">';
echo '<thead>';
echo '<tr><th colspan="3" class="text-center lightgray">연동제어기</th></tr>';
echo '<tr>';
echo '<th class="text-center lightgray">품명</th>';
echo '<th class="text-center lightgray">수량</th>';
echo '<th class="text-center yellowblackBold "> 입고 LOT NO.</th>';
echo '<tr>';
echo '</thead>';
echo '<tbody>';
$control_labels = ['매립형', '노출형', '뒷박스'];
for ($i = 0; $i < count($other_columns); $i++) {
if (intval(trim($other_columns[$i])) !== 0 && $other_columns[$i] !== '0') {
if ($control_labels[$i]=== '뒷박스') {
// $code = '연동제어기-' . $control_labels[$i];
$code = 'EGI1.15T-1219*2438';
} else {
$code = '연동제어기-' . $control_labels[$i] . '(' . $wireless . ')';
}
echo '<tr>';
echo '<td class="text-center">' . $control_labels[$i] . '</td>';
echo '<td class="text-center">' . $other_columns[$i] . '</td>';
echo '<td class="text-center w160px yellowblackBold">
<div class="d-flex justify-content-center align-items-center">
<input type="text" class="form-control noborder-input lotnumInput" autocomplete="off" placeholder="로트번호" data-itemname="' . $code . '" data-usesurang="" name="lotnum_side[]" />
<div class="info-btn" data-lotnum="" data-bs-toggle="tooltip" data-bs-placement="left" title="성적서"> <i class="bi bi-info-circle-fill"></i> </div>
</div>
</td>';
echo '</tr>';
}
}
echo '</tbody>';
echo '</table>';
echo '</div>'; // 연동제어기 부분 끝
echo '</div>'; // row 끝
}
$rowCounter++; } // end of motor 체크박스 ?>
<!-- 슬랫 체크 되어 있으면 슬랫 출력 -->
<?php if(isset($slatcheck) && $slatcheck === '1') { ?>
<div class="row mt-2 ">
<div class="d-flex align-items-center justify-content-start">
<?php echo $rowCounter . '. 슬랫(SLAT) - EGI 1.55T'; ?>
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/' . $tablename . '/common/slat.php'; ?> <!-- 모터, 발주서, 출고증, 확인서 등등 공통 -->
<?php } // end of slatcheck 체크박스 ?>
<!-- 절곡품 체크 되어 있으면 절곡품 출력 -->
<?php if(isset($steel) && $steel === '1') { ?>
<div class="row mt-2 ">
<div class="d-flex align-items-center justify-content-start">
<?php echo $rowCounter . '. 절곡품'; ?>
<br>
<?php
// 가이드레일 정보 표시
if (trim($prodCode) == "KTE01") {
$result = $rowCounter . "-1. 가이드레일 - EGI 1.55T ";
} else {
$result = $rowCounter . "-1. 가이드레일 - SUS 1.55T ";
}
echo $result;
?>
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/' . $tablename . '/common/guiderail_slat.php'; ?> <!-- 가이드레일 공통사항 발주서 등 -->
<?php include $_SERVER['DOCUMENT_ROOT'] . '/' . $tablename . '/common/shutterbox_slat.php'; ?> <!-- 출고증, 발주서 등등 공통셔터박스 내용 -->
<div class="row mt-2">
<div class="d-flex justify-content-start"> <?php echo $rowCounter . '-2. 하단마감재 '; ?> <br>
<?php
if (trim($prodcode) == "KTE01") {
$result = "하단마감재(EGI 1.55T) ";
} else {
$result = "하단마감재(SUS 1.55T) ";
}
echo $result . '</div></div>' ;
?>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/' . $tablename . '/common/bottombar_slat.php'; ?> <!-- 하단마감재 발주서 등등 공통 -->
<?php } // end of steel 체크박스 ?>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/' . $tablename . '/common/etc.php'; ?> <!-- 소모품 등 발주서 등등 공통 -->
</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>
</form>
<!-- 페이지로딩 -->
<script>
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
if(loader)
loader.style.display = 'none';
});
function generatePDF() {
var workplace = '<?php echo $title_message; ?>';
var today = new Date();
var formattedDate = "(" + String(today.getFullYear()).slice(-2) + "." + ("0" + (today.getMonth() + 1)).slice(-2) + "." + ("0" + today.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: 1 },
html2canvas: {
scale: 3, // ★★★ 해상도(기본은 1) → 2~4 정도로 높이면 선명해짐 4는 용량이 매우 큽니다. 보통 3M 이상
useCORS: true,
scrollY: 0,
scrollX: 0,
windowWidth: document.body.scrollWidth,
windowHeight: document.body.scrollHeight
},
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
pagebreak: {
mode: ['css', 'legacy'],
avoid: ['tr', '.avoid-break'] // 핵심
}
};
html2pdf().from(element).set(opt).save();
}
function generatePDF_server(callback) {
var workplace = '<?php echo $title_message; ?>';
var item = '<?php echo $emailTitle; ?>';
var today = new Date();
var formattedDate = "(" + String(today.getFullYear()).slice(-2) + "." + ("0" + (today.getMonth() + 1)).slice(-2) + "." + ("0" + today.getDate()).slice(-2) + ")";
var result = 'KD' + item +'(' + 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: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
pagebreak: { mode: [''] }
};
html2pdf().from(element).set(opt).output('datauristring').then(function (pdfDataUri) {
var pdfBase64 = pdfDataUri.split(',')[1]; // Base64 인코딩된 PDF 데이터 추출
var formData = new FormData();
formData.append('pdf', pdfBase64);
formData.append('filename', result);
$.ajax({
type: 'POST',
url: '/email/save_pdf.php', // PDF 파일을 저장하는 PHP 파일
data: formData,
processData: false,
contentType: false,
success: function (response) {
var res = JSON.parse(response);
if (callback) {
callback(res.filename); // 서버에 저장된 파일 경로를 콜백으로 전달
}
},
error: function (xhr, status, error) {
Swal.fire('Error', 'PDF 저장에 실패했습니다.', 'error');
}
});
});
}
var ajaxRequest = null;
function sendmail() {
var secondordnum = '<?php echo $secondordnum; ?>'; // 서버에서 가져온 값
var item = '<?php echo $emailTitle; ?>';
if (!secondordnum) {
Swal.fire({
icon: 'warning',
title: '오류 알림',
text: '발주처 코드가 없습니다.'
});
return; // 함수 종료
}
if (typeof ajaxRequest !== 'undefined' && ajaxRequest !== null) {
ajaxRequest.abort();
}
ajaxRequest = $.ajax({
type: 'POST',
url: '/email/get_companyCode.php',
data: { secondordnum: secondordnum },
dataType: 'json',
success: function(response) {
console.log('response : ', response);
if (response.error) {
Swal.fire('Error', response.error, 'error');
} else {
var email = response.email;
var vendorName = response.vendor_name;
Swal.fire({
title: 'E메일 보내기',
text: vendorName + ' Email 주소확인',
icon: 'warning',
input: 'text', // input 창을 텍스트 필드로 설정
inputLabel: 'Email 주소 수정 가능',
inputValue: email, // 기존 이메일 주소를 기본값으로 설정
showCancelButton: true,
confirmButtonText: '보내기',
cancelButtonText: '취소',
reverseButtons: true,
inputValidator: (value) => {
if (!value) {
return '이메일 주소를 입력해주세요!';
}
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(value)) {
return '올바른 이메일 형식을 입력해주세요!';
}
}
}).then((result) => {
if (result.isConfirmed) {
const updatedEmail = result.value; // 입력된 이메일 주소 가져오기
generatePDF_server(function(filename) {
sendEmail(updatedEmail, vendorName, item, filename);
});
}
});
}
},
error: function(xhr, status, error) {
Swal.fire('Error', '전송중 오류가 발생했습니다.', 'error');
}
});
}
function sendEmail(recipientEmail, vendorName, item, filename) {
if (typeof ajaxRequest !== 'undefined' && ajaxRequest !== null) {
ajaxRequest.abort();
}
var today = new Date();
var formattedDate = "(" + String(today.getFullYear()).slice(-2) + "." + ("0" + (today.getMonth() + 1)).slice(-2) + "." + ("0" + today.getDate()).slice(-2) + ")";
ajaxRequest = $.ajax({
type: 'POST',
url: '/email/send_email.php', // 이메일 전송을 처리하는 PHP 파일
data: { email: recipientEmail, vendorName: vendorName, filename: filename, item: item, formattedDate: formattedDate },
success: function(response) {
console.log(response);
Swal.fire('Success', '정상적으로 전송되었습니다.', 'success');
},
error: function(xhr, status, error) {
Swal.fire('Error', '전송에 실패했습니다. 확인바랍니다.', 'error');
}
});
}
$(document).ready(function() {
var selectedItemName = ''; // itemName을 저장할 변수
var selectedusesurang = ''; // itemName을 저장할 변수
// lotnumInput 클릭 시 itemName을 저장
$(document).on('click', '.lotnumInput', function() {
var row = $(this).closest('tr');
selectedRow = row; // tr 요소 저장
selectedItemName = $(this).data('itemname'); // itemName 저장
selectedusesurang = $(this).data('usesurang'); // usesurang 저장
console.log(selectedItemName);
if (selectedItemName) {
loadLotData('material', selectedItemName, selectedusesurang);
setTimeout(function() {
$('#lotModal').modal('show');
}, 1000);
} else {
alert('품목명을 입력해주세요.');
}
});
$('#material-tab').on('shown.bs.tab', function() {
if (selectedItemName) {
loadLotData('material', selectedItemName, selectedusesurang);
}
});
$('#lotModal').on('shown.bs.modal', function() {
if (selectedItemName) {
loadLotData('material', selectedItemName, selectedusesurang);
}
});
});
// 로트번호 데이터를 불러오는 함수
function loadLotData(type, itemName, usesurang) {
$.post('fetch_lot_COD.php', { lot_type: type, item_name: itemName, usesurang : usesurang })
.done(function(data) {
if (type === 'material') {
$('#material').html(data);
}
})
.fail(function(xhr, status, error) {
console.error("AJAX Request Failed:", status, error);
alert("로트 데이터를 불러오는 중 오류가 발생했습니다.");
});
}
// 선택한 로트 번호를 적용하는 함수
function selectLotNumber_prod(lotNumber) {
selectedRow.find('input.lotnumInput').val(lotNumber);
$('#lotModal').modal('hide');
}
// 절곡로트번호 공백 삽입
$(document).on('click', '.nullBtn_bending', function() {
selectLotNumber_prod('');
});
function selectLotNumber(lotNumber) {
// motor-lot 필드가 선택되었는지 확인
console.log('selectLotNumber 호출됨, lotNumber:', lotNumber);
// 선택된 로트 번호를 motor-lot 및 lotnumInput 필드에 설정
selectedRow.find('input.motor-lot').val(lotNumber).trigger('input'); // input 이벤트 트리거
selectedRow.find('input.lotnumInput').val(lotNumber);
selectedRow.find('.info-btn').attr('data-lotnum', lotNumber); // 내부의 .info-btn 선택
// 모달 닫기
$('#lotModal').modal('hide');
}
$(document).ready(function() {
// 모든 모터 lotnumInput 필드에 대해 변경 이벤트 리스너 추가
$('.motor-lot').on('input', function() {
// input 이벤트가 발생했음을 확인
console.log('motor-lot input 이벤트 발생');
// 현재 모터 입력 필드의 인덱스를 가져옴
const index = $(this).data('index');
const lotValue = $(this).val();
console.log('motor lot 선택됨', lotValue, 'index:', index);
// 해당 인덱스를 가진 브라켓 lotnumInput 필드를 찾아 값을 설정
const $bracketInput = $('.bracket-lot[data-index="' + index + '"]');
if ($bracketInput.length) {
$bracketInput.val(lotValue);
console.log('bracket-lot 설정됨:', lotValue, 'index:', index);
} else {
console.log('해당 인덱스의 bracket-lot을 찾을 수 없음:', index);
}
});
});
$(document).on('click', '.nullBtn', function() {
selectLotNumber('');
});
$(document).on('click', '.cancelBtn', function() {
$('#lotModal').modal('hide');
});
$(document).on('click', '.saveData', function() {
saveData();
});
$(document).on('click', '.lot-done-btn', function() {
const num = $(this).data('num');
const tablename = $(this).data('tablename');
const rawitemname = $(this).data('rawitemname');
const lottype = $(this).data('lottype');
const usesurang = $(this).closest('tr').find('.usesurang').text(); // 사용 수량을 가져옴
const currentRow = $(this).closest('tr'); // 현재 tr 요소 저장
console.log('num:', num);
console.log('tablename:', tablename);
console.log('lottype:', lottype);
console.log('usesurang:', usesurang);
console.log('rawitemname:', rawitemname);
Swal.fire({
title: '로트 소진 처리',
text: '해당 로트를 소진 처리하시겠습니까?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '예, 처리합니다',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
$.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(() => {
// 해당 tr 요소 제거
currentRow.remove();
});
} else {
Swal.fire({
title: '오류',
text: '소진 처리 중 오류가 발생했습니다.',
icon: 'error',
confirmButtonText: '확인'
});
}
},
error: function(xhr, status, error) {
Swal.fire({
title: 'AJAX 오류',
text: '요청 중 오류가 발생했습니다.',
icon: 'error',
confirmButtonText: '확인'
});
}
});
}
});
});
// 결재 취소 기능
$(document).on('click', '.remove-approval', function() {
// 승인자 정보를 지우고 화면에서 숨김
$('#approvalDisplay').html('').hide();
// JSON 데이터에서 승인자의 정보 제거
let formData = JSON.parse($('#COD').val() || '[]');
const approvalIndex = formData.findIndex(item => item.approval);
if (approvalIndex !== -1) {
formData[approvalIndex].approval.approver.name = '';
formData[approvalIndex].approval.approver.date = '';
}
// JSON 문자열로 다시 저장
$('#COD').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() {
// 결재 부분 정보 저장
let approvalData = {
writer: {
name: $('#writerDisplay').html().split('<br>')[0] || '',
date: $('#writerDisplay').html().split('<br>')[1] || ''
},
reviewer: {
name: $('#reviewerDisplay').html().split('<br>')[0] || '',
date: $('#reviewerDisplay').html().split('<br>')[1] || ''
},
approver: {
name: $('#approvalDisplay').clone().children('i').remove().end().html().split('<br>')[0] || '',
date: $('#approvalDisplay').clone().children('i').remove().end().html().split('<br>')[1] || ''
}
};
let formData = [];
formData.push({ approval: approvalData });
// 입고 LOT NO 정보 저장 (행별)
let lotNums = [];
$('.lotnumInput').each(function() {
lotNums.push($(this).val());
});
formData.push({ lotNumbers: lotNums });
// 추가 정보 저장
formData.push({ num: $('#num').val() });
formData.push({ tablename: $('#tablename').val() });
formData.push({ update_log: $('#update_log').val() });
// JSON 문자열로 변환
let jsonString = JSON.stringify(formData);
// 숨겨진 필드에 JSON 데이터 설정
$('#COD').val(jsonString);
$("#overlay").show(); // 오버레이 표시
$("button").prop("disabled", true); // 모든 버튼 비활성화
// 폼데이터 전송시 사용함 Get form
var form = $('#board_form')[0];
var datasource = new FormData(form);
showMsgModal(2); // 파일저장중
$.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
url: "insert_COD.php",
type: "post",
data: datasource,
dataType: "json",
success: function(data) {
// console.log(data);
setTimeout(function() {
$("button").prop("disabled", false); // 모든 버튼 활성화
hideMsgModal();
$("#overlay").hide(); // 오버레이 숨김
Toastify({
text: "저장완료",
duration: 3000,
close: true,
gravity: "top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
}, 1000);
},
error: function(jqxhr, status, error) {
console.log(jqxhr, status, error);
alert("An error occurred: " + error);
}
});
}
$(document).ready(function() {
if (CODData.length > 0) {
console.log(CODData);
// 결재 부분 정보
const approval = CODData.find(item => item.approval);
if (approval) {
// 작성자 정보 표시
$('#writerDisplay').html(
(approval.approval.writer.name || '') + '<br>' + (approval.approval.writer.date || '')
);
// 검토자 정보 표시
$('#reviewerDisplay').html(
(approval.approval.reviewer.name || '') + '<br>' + (approval.approval.reviewer.date || '')
);
// 승인자 정보 표시
if (approval.approval.approver.name && approval.approval.approver.date) {
$('#approvalDisplay').show();
$('#approvalDisplay').html(
approval.approval.approver.name + '<br>' + approval.approval.approver.date +
' <i class="bi bi-x-circle remove-approval" style="cursor: pointer;"></i>'
);
} else {
// 승인 정보가 없을 때는 공백으로 처리
$('#approvalDisplay').hide().html('');
}
}
// 입고 LOT NO 정보
const lotNumbers = CODData.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] || '');
});
}
// 업데이트 로그가 있을 경우 표시
const updateLog = CODData.find(item => item.update_log);
if (updateLog) {
$('#update_log').val(updateLog.update_log || '');
}
}
});
// 부트스트랩 툴팁
$(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).on('click', '.clickable', function() {
const isQCadmin = <?= json_encode($QCadmin); ?>; // 관리자인 경우 true
const userName = <?= json_encode($user_name); ?>; // 현재 사용자 이름
const todayStr = <?= json_encode($todayStr); ?>; // 오늘 날짜
let targetId = $(this).attr('id') + 'Display';
// 작성과 검토는 누구나 가능
if ($(this).attr('id') === 'writer' || $(this).attr('id') === 'reviewer') {
$('#' + targetId).html(userName + '<br>' + todayStr);
}
// 승인 버튼은 관리자만 가능
else if ($(this).attr('id') === 'approver') {
if (!isQCadmin) {
alert('승인 권한이 없습니다.');
return;
}
// 승인자의 이름과 오늘 날짜 표시
$('#approvalDisplay').html(
userName + '<br>' + todayStr +
' <i class="bi bi-x-circle remove-approval" style="cursor: pointer;"></i>'
);
$('#approvalDisplay').show();
// 결재 정보를 업데이트하여 저장 로직에 반영
updateApprovalData(userName, todayStr);
saveData(); // 저장까지 실행하기
}
});
// 결재 정보 업데이트 함수
function updateApprovalData(userName, date) {
let approvalData = {
writer: {
name: $('#writerDisplay').text().split('<br>')[0] || '',
date: $('#writerDisplay').text().split('<br>')[1] || ''
},
reviewer: {
name: $('#reviewerDisplay').text().split('<br>')[0] || '',
date: $('#reviewerDisplay').text().split('<br>')[1] || ''
},
approver: {
name: $('#approvalDisplay').text().split('<br>')[0] || '',
date: $('#approvalDisplay').text().split('<br>')[1] || ''
}
};
let formData = JSON.parse($('#COD').val() || '[]');
const approvalIndex = formData.findIndex(item => item.approval);
if (approvalIndex !== -1) {
formData[approvalIndex].approval = approvalData;
} else {
formData.push({ approval: approvalData });
}
$('#COD').val(JSON.stringify(formData));
}
ajaxRequest1 = null;
$(document).on('click', '.info-btn, .info-wire-btn', function () {
var lotnum = $(this).data('lotnum');
console.log('lotnum :', lotnum);
if (!lotnum) {
Swal.fire('알림', '로트번호를 입력하세요.', 'warning');
return;
}
if (ajaxRequest1 !== null) {
ajaxRequest1.abort();
}
ajaxRequest1 = $.ajax({
url: 'fetch_certificate.php',
type: 'POST',
data: { lotnum: lotnum },
dataType: 'json',
success: function (response) {
console.log('response :',response);
if (response.success) {
if (response.item === "offering") {
// 제공품 성적서
var url = "/lot/write_sheet.php?num=" + response.num;
customPopup(url, '제공품 성적서', 800, 900);
} else if (response.item === "regular") {
// 일반 성적서 데이터 처리
viewBoardInstock(
response.num,
response.itemname,
response.specification,
response.remarks
);
}
} else {
Swal.fire('오류', response.message, 'error');
}
},
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 여기에 viewBoardInstock() 함수 들어있음 -->
</body>
</html>