Files
sam-kd/instock/list.php

754 lines
27 KiB
PHP
Raw Normal View History

<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
sleep(1);
header("Location:" . $WebSite . "login/login_form.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
$title_message = '수입검사 관리대장';
// 품질담당자 및 관리자인 경우 권한 부여
$QCadmin = 0 ;
if($user_name=='이세희' || $user_name=='개발자' || $user_name=='함신옥' || $user_name=='노완호' )
$QCadmin = 1 ;
?>
<link href="css/style.css" rel="stylesheet">
<title> <?=$title_message?> </title>
</head>
<body>
<?php
$header = isset($_REQUEST['header']) ? $_REQUEST['header'] : '';
if($header ==='header')
require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php');
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
function checkNull($strtmp) {
return ($strtmp !== null && trim($strtmp) !== '');
}
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$mode = isset($_REQUEST["mode"]) ? $_REQUEST["mode"] : '';
$fromdate = isset($_REQUEST['fromdate']) ? $_REQUEST['fromdate'] : '';
$todate = isset($_REQUEST['todate']) ? $_REQUEST['todate'] : '';
$tablename = 'instock';
// `instock` 테이블에서 `item_name` 컬럼 값 가져오기
$sql = "SELECT item_name FROM {$DB}.{$tablename} WHERE is_deleted IS NULL";
try {
$stmh = $pdo->query($sql);
$itemNames = $stmh->fetchAll(PDO::FETCH_COLUMN, 0); // item_name 컬럼의 값을 배열로 저장
// 중복 제거
$uniqueItemNames = array_unique($itemNames);
// 결과 출력 (예: 배열 확인용)
// print_r($uniqueItemNames);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// 현재 날짜
$currentDate = date("Y-m-d");
// fromdate 또는 todate가 빈 문자열이거나 null인 경우 기본 날짜 설정
if ($fromdate === "" || $fromdate === null || $todate === "" || $todate === null) {
$fromdate = date("Y-m-d", strtotime("-32 weeks", strtotime($currentDate))); // 16주 전
$todate = date("Y-m-d", strtotime("+3 months", strtotime($currentDate))); // 3개월 후
$Transtodate = $todate;
} else {
$Transtodate = $todate; // 설정된 기간
}
$SettingDate = "inspection_date"; // 정렬 기준 날짜
$order = " ORDER BY inspection_date DESC, lot_no asc ";
if(checkNull($search)) {
$sql = "SELECT * FROM {$DB}.{$tablename}
WHERE inspection_date BETWEEN date('$fromdate') AND date('$Transtodate') AND searchtag LIKE '%$search%' AND is_deleted IS NULL " . $order;
} else {
$sql = "SELECT * FROM ".$DB.".".$tablename . " WHERE inspection_date BETWEEN date('$fromdate') AND date('$Transtodate') AND is_deleted IS NULL " . $order;
}
try {
$stmh = $pdo->query($sql);
$total_row = $stmh->rowCount();
?>
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">
<input type="hidden" id="mode" name="mode" value="<?=$mode?>">
<input type="hidden" id="num" name="num">
<input type="hidden" id="tablename" name="tablename" value="<?=$tablename?>">
<input type="hidden" id="header" name="header" value="<?=$header?>">
<input type="hidden" id="QCadmin" name="QCadmin" value="<?=$QCadmin?>">
<div class="container-fluid">
<!-- Modal -->
<div id="myModal" class="modal">
<div class="modal-content" style="width:850px;">
<div class="modal-header">
<span class="modal-title">수입검사</span>
<span class="close">&times;</span>
</div>
<div class="modal-body">
<div class="custom-card"></div>
</div>
</div>
</div>
</div>
<?php
if ($header == 'header') {
print '<div class="container-fluid">';
print '<div class="card justify-content-center text-center mt-1">';
} else {
print '<div class="container">';
print '<div class="card justify-content-center text-center mt-5">';
}
?>
<div class="card-header">
<div class="d-flex p-1 m-1 mt-1 justify-content-center align-items-center ">
<h5> <?=$title_message?> </h5> &nbsp;&nbsp;&nbsp;&nbsp;
<button type="button" class="btn btn-dark btn-sm " onclick='location.reload();' > <i class="bi bi-arrow-clockwise"></i> </button>
</div>
<?php
// 서버에 저장된 로트번호 불러오기
$filepath = $_SERVER['DOCUMENT_ROOT'] . '/instock/lotnum.txt';
if (file_exists($filepath)) {
// 파일에서 로트번호 읽기
$receivedlotNum = file_get_contents($filepath);
} else {
$receivedlotNum = '로트번호가 없습니다.'; // 파일이 없을 경우 기본 메시지
}
?>
<div class="d-flex p-1 m-1 mt-2 mb-1 justify-content-center align-items-center ">
<span class="text-secondary"> 신규 작성시 로트번호는 년도(2자리) + (2자리) + (2자리) - 일련번호 형태로 초기 생성, 예시) 241128-01 </span>
<span class="badge bg-primary ms-3"> 서버 생성완료 : <?=$receivedlotNum?> </span>
</div>
</div>
<div class="card-body">
<div class="container mt-2 mb-2">
<div class="row">
<div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-center align-items-center">
<?= $total_row ?> &nbsp;
<button type="button" id="premonth" class="btn btn-dark btn-sm me-1 " onclick='yesterday()' > 전일 </button>
<button type="button" class="btn btn-outline-dark btn-sm me-1 " onclick='this_today()' > 금일 </button>
<button type="button" class="btn btn-dark btn-sm me-1 " onclick='this_tomorrow()' > 익일 </button>
<input type="date" id="fromdate" name="fromdate" class="form-control" style="width:100px;" value="<?=$fromdate?>" > &nbsp; ~ &nbsp;
<input type="date" id="todate" name="todate" class="form-control me-1" style="width:100px;" value="<?=$todate?>" > &nbsp;
<div class="inputWrap">
<input type="text" id="search" name="search" value="<?=$search?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off" class="form-control" style="width:150px;" > &nbsp;
<button class="btnClear"></button>
</div>
<div id="autocomplete-list">
</div>
&nbsp;
<button id="searchBtn" type="button" class="btn btn-dark btn-sm" > <i class="bi bi-search"></i> 검색 </button>
<button id="newBtn" type="button" class="btn btn-dark btn-sm ms-2 me-2"> <i class="bi bi-pencil-square"></i> 신규 </button>
<?php if($user_name=='개발자') { ?>
<button id="uploadBtn" type="button" class="btn btn-dark btn-sm me-2"> <i class="bi bi-box-arrow-up"></i> 업로드 </button>
<?php } ?>
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover" id="myTable">
<thead class="table-primary">
<th class="text-center" style="width:50px;" >번호</th>
<th class="text-center" style="width:90px;" >로트번호</th>
<th class="text-center" style="width:60px;" >판정</th>
<th class="text-center" style="width:60px;" >성적서</th>
<th class="text-center" style="width:60px;" >소진</th>
<th class="text-center" style="width:100px;">품목코드</th>
<th class="text-center" style="width:80px;" >검사일</th>
<th class="text-center" style="width:80px;" >납품업체</th>
<th class="text-center" style="width:200px;" >품목명</th>
<th class="text-center" style="width:200px;" >규격</th>
<th class="text-center" style="width:40px;" > 단위</th>
<th class="text-center" style="width:50px;" >입고량</th>
<th class="text-center" style="width:120px;" >자재번호</th>
<th class="text-center" style="width:120px;" >제조사</th>
<th class="text-center" style="width:100px;" >비고</th>
<th class="text-center" style="width:90px;" >매입가 <br>(VAT별도)</th>
<th class="text-center" style="width:80px;" >중량(KG)</th>
</thead>
<tbody>
<?php
$start_num = $total_row;
while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
include '_row.php';
$specification_clean = preg_replace('/\s+/', ' ', $specification); // 연속된 공백을 하나의 공백으로 변경
$remarks_clean = preg_replace('/\s+/', ' ', $remarks); // 연속된 공백을 하나의 공백으로 변경
// JSON을 배열로 디코딩
$iListArray = json_decode($iList, true);
// resultJudgement 값을 찾기 위한 루프
$resultJudgement = null;
foreach ($iListArray as $item) {
// 배열에서 inputItems를 가진 항목이 있는지 확
if (isset($item['inputItems']['resultJudgement'])) {
$resultJudgement = $item['inputItems']['resultJudgement'];
break; // 값을 찾으면 루프 종료
}
}
?>
<tr data-num="<?= $row['num'] ?>"
data-itemname="<?= htmlspecialchars($row['item_name']) ?>"
data-specification="<?= htmlspecialchars($row['specification']) ?>"
data-remarks="<?= htmlspecialchars($row['remarks']) ?>">
<td class="text-center" onclick="loadForm('update', '<?=$row['num']?>');"><?= $start_num ?></td>
<td class="text-center fw-bold text-success" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['lot_no'] ?></td>
<?php
$class = ($resultJudgement === '합격') ? 'text-dark' : 'text-danger';
?>
<td class="text-center fw-bold <?= $class ?>" onclick="loadForm('update', '<?=$row['num']?>');"><?= $resultJudgement ?></td>
<td class="text-center view-import-inspection">
<span class="badge bg-secondary">성적서</span>
</td>
<td class="text-center" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['lotDone'] ?></td>
<td class="text-center" style="word-nowrap: break-word;" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['prodcode'] ?></td>
<td class="text-center" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['inspection_date'] ?></td>
<td class="text-center" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['supplier'] ?></td>
<td class="text-start fw-bold text-primary" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['item_name'] ?></td>
<td class="text-start text-secondary" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['specification'] ?></td>
<td class="text-center fw-bold text-secondary" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['unit'] ?></td>
<td class="text-end fw-bold text-primary" onclick="loadForm('update', '<?=$row['num']?>');">
<?php if (is_numeric($row['received_qty'])) : ?>
<?= number_format($row['received_qty']) ?>
<?php else : ?>
<?= htmlspecialchars($row['received_qty']) ?>
<?php endif; ?>
</td>
<td class="text-start fw-bold text-secondary" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['material_no'] ?></td>
<td class="text-center" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['manufacturer'] ?></td>
<td class="text-start" onclick="loadForm('update', '<?=$row['num']?>');"><?= $row['remarks'] ?></td>
<td class="text-end" onclick="loadForm('update', '<?=$row['num']?>');">
<?= is_numeric($row['purchase_price_excl_vat']) ? number_format($row['purchase_price_excl_vat']) : '' ?>
</td>
<?php
$weight_kg = $row['weight_kg'];
$weight_kg = str_replace(',', '', $weight_kg);
if (is_numeric($weight_kg) && $weight_kg != '' && $weight_kg != '0') {
$weight_kg = number_format((float)$weight_kg);
}
?>
<td class="text-end" onclick="loadForm('update', '<?=$row['num']?>');"><?= $weight_kg ?></td>
</tr>
<?php
$start_num--;
}
} catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
?>
</tbody>
</table>
</div>
</div>
</div>
</form>
<script>
var ajaxRequest = null;
var itemData = [];
var lotnumData = [];
function loadForm(mode, num = null) {
if (num == null) {
$("#mode").val('insert');
} else {
$("#mode").val('update');
$("#num").val(num);
}
if(mode =='copy')
$("#mode").val(mode);
$.ajax({
type: "POST",
url: "fetch_inspection.php",
data: { mode: mode, num: num },
dataType: "html",
success: function(response) {
document.querySelector(".modal-body .custom-card").innerHTML = response;
$("#myModal").show();
// '직접입력' 선택 시 모달 띄우기
$('#supplier').on('change', function () {
if ($(this).val() === 'direct') {
$('#supplierModal').modal('show'); // 모달 띄우기
}
});
// 모달에서 입력된 값 추가
$('#addSupplierBtn').on('click', function () {
const newSupplier = $('#newSupplierInput').val().trim(); // 입력 값
if (newSupplier) {
// '선택' 옵션 이전에 새 옵션 추가
$('#supplier option[value=""]').after(`<option value="${newSupplier}" selected>${newSupplier}</option>`);
$('#supplier').val(newSupplier); // 새로 추가된 값 선택
$('#supplierModal').modal('hide'); // 모달 닫기
} else {
alert('값을 입력해주세요.');
}
});
// 제조사 - '직접입력' 선택 시 모달 띄우기
$('#manufacturer').on('change', function () {
if ($(this).val() === 'direct') {
$('#manufacturerModal').modal('show'); // 모달 띄우기
}
});
// 모달에서 입력된 값 추가 (제조사)
$('#addManufacturerBtn').on('click', function () {
const newManufacturer = $('#newManufacturerInput').val().trim(); // 입력 값
if (newManufacturer) {
$('#manufacturer option[value=""]').after(`<option value="${newManufacturer}" selected>${newManufacturer}</option>`);
$('#manufacturer').val(newManufacturer); // 새로 추가된 값 선택
$('#manufacturerModal').modal('hide'); // 모달 닫기
} else {
alert('값을 입력해주세요.');
}
});
// 단위 - '직접입력' 선택 시 모달 띄우기
$('#unit').on('change', function () {
if ($(this).val() === 'direct') {
$('#unitModal').modal('show'); // 모달 띄우기
}
});
// 모달에서 입력된 값 추가 (단위)
$('#addUnitBtn').on('click', function () {
const newUnit = $('#newUnitInput').val().trim(); // 입력 값
if (newUnit) {
$('#unit option[value=""]').after(`<option value="${newUnit}" selected>${newUnit}</option>`);
$('#unit').val(newUnit); // 새로 추가된 값 선택
$('#unitModal').modal('hide'); // 모달 닫기
} else {
alert('값을 입력해주세요.');
}
});
$(document).on('change', '#item_name', function () {
const selectedItem = $(this).val();
const specification = $("#specification").val();
console.log('selectedItem :', selectedItem);
console.log('specification :', specification);
if (!selectedItem) {
$('#specification').html('<option value="">선택</option>').prop('disabled', true);
$('#prodcode').val('');
return;
}
// 규격 목록 가져오기
$.ajax({
type: 'POST',
url: 'fetch_code.php',
data: { mode: 'fetch_specifications', item_name: selectedItem },
dataType: 'json',
success: function (response) {
console.log(response);
if (!response.success) {
console.error(response.error);
return;
}
let options = '<option value="">선택</option>';
// 중복 제거 및 오름차순 정렬
const uniqueSortedData = [...new Set(response.data)].sort();
uniqueSortedData.forEach(spec => {
options += `<option value="${spec}">${spec}</option>`;
});
$('#specification').html(options).prop('disabled', false); // 규격 Select 업데이트
},
error: function (jqxhr, status, error) {
console.error('AJAX Error:', status, error);
}
});
});
$(document).on('change', '#specification', function () {
const selectedItem = $('#item_name').val();
const selectedSpec = $(this).val();
if (!selectedItem || !selectedSpec) {
$('#prodcode').val('');
return;
}
// 품목코드 업데이트
const prodcode = `${selectedItem}-${selectedSpec}`;
$('#prodcode').val(prodcode); // 품목코드 필드에 값 설정
});
$("#closeBtn").on("click", function() {
$("#myModal").hide();
});
$(document).on('click', '.specialbtnClear', function(e) {
e.preventDefault();
$(this).siblings('input').val('').focus();
$('#item_name').val('');
$('#material_no').val('');
});
$(document).on('click', '.btnClear_lot', function(e) {
e.preventDefault();
$(this).siblings('input').val('').focus();
$('#lot_no').val('');
});
$(document).on('input', '.inputcode ', function() {
initializeAutocomplete(this);
});
$(document).on('input', '.inputitemname ', function() {
initializeAutocomplete(this);
});
$(document).on('input', '.inputlot ', function() {
initializeAutocomplete(this);
});
$(document).off("click", "#viewinspection").on("click", "#viewinspection", function(event) {
// 버튼의 data 속성에서 값을 직접 가져옵니다.
var num = $(this).data('num');
var itemname = $(this).data('itemname');
var spec = $(this).data('specification');
var remarks = $(this).data('remarks');
// 클릭 이벤트 전파 방지
event.stopPropagation();
// viewBoardInstock 함수 호출
viewBoardInstock(num, itemname, spec, remarks);
});
let isSaving = false;
$("#saveBtn").on("click", function() {
const myform = document.getElementById('board_form');
const inputs = myform.querySelectorAll('input[required], select[required]'); // input, select 요소 중 required 속성 있는 것 선택
let allValid = true;
// console.log(inputs);
inputs.forEach(input => {
if (!input.value) {
allValid = false;
Toastify({
text: "필수입력 부분을 확인해 주세요.",
duration: 2000,
close:true,
gravity:"top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
return
}
});
if(!allValid )
return
if (isSaving) return;
isSaving = true;
let header = $("#header").val();
let formData = $("#board_form").serialize();
let continuousRegistration = $("#continuous_registration").is(':checked');
// 로트 번호 생성
let lot_no = $("#lot_no").val();
// 서버에 데이터 저장
$.ajax({
url: "save_lotnum.php", // 파일 저장 PHP
type: "post",
data: { lot_no: lot_no },
success: function(response) {
if (response.status === 'success') {
console.log("Data saved successfully:", response.message);
} else {
console.error("Error saving data:", response.message);
}
// 기존 저장 로직 실행
$.ajax({
url: "insert.php",
type: "post",
data: formData,
success: function(response) {
Toastify({
text: "저장완료",
duration: 3000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#4fbe87",
}).showToast();
if (!continuousRegistration) {
$("#myModal").hide();
location.reload();
} else {
$("#mode").val('insert');
$("#num").val('');
isSaving = false;
}
},
error: function(jqxhr, status, error) {
console.log(jqxhr, status, error);
isSaving = false;
}
});
},
error: function(jqxhr, status, error) {
console.log("File save error:", jqxhr, status, error);
isSaving = false;
}
});
});
$("#copyBtn").on("click", function() {
const num = $("#num").val();
$("#myModal").modal('hide');
loadForm('copy', num);
});
$("#deleteBtn").on("click", function() {
var QCadmin = $("#QCadmin").val() ;
if (QCadmin !== '1') {
Swal.fire({
title: '삭제불가',
text: "관리자만 삭제 가능합니다.",
icon: 'error',
confirmButtonText: '확인'
});
return;
}
Swal.fire({
title: '자료 삭제',
text: "삭제는 신중! 정말 삭제하시겠습니까?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '삭제',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
$("#mode").val('delete');
var formData = $("#board_form").serialize();
$.ajax({
url: "insert.php",
type: "post",
data: formData,
success: function(response) {
Toastify({
text: "파일 삭제완료",
duration: 2000,
close: true,
gravity: "top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
$("#myModal").hide();
location.reload();
},
error: function(jqxhr, status, error) {
console.log(jqxhr, status, error);
}
});
}
});
});
},
error: function(jqxhr, status, error) {
console.log("AJAX Error: ", status, error);
}
});
}
</script>
<script>
var ajaxRequest_write = null;
var dataTable;
var material_regpageNumber;
$(document).ready(function() {
dataTable = $('#myTable').DataTable({
"paging": true,
"ordering": true,
"searching": true,
"pageLength": 30,
"lengthMenu": [ 30,50, 100, 200, 500, 1000],
"language": {
"lengthMenu": "Show _MENU_ entries",
"search": "Live Search:"
},
"order": [[1, 'desc']],
"dom": 't<"bottom"ip>'
});
var savedPageNumber = getCookie('material_regpageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
dataTable.on('page.dt', function() {
var material_regpageNumber = dataTable.page.info().page + 1;
setCookie('material_regpageNumber', material_regpageNumber, 10);
});
$('#myTable_length select').on('change', function() {
var selectedValue = $(this).val();
dataTable.page.len(selectedValue).draw();
savedPageNumber = getCookie('material_regpageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
});
$(document).on('click', '.specialbtnClear', function(e) {
e.preventDefault();
$(this).siblings('input').val('').focus();
});
$(document).on('click', '.btnClear_lot', function(e) {
e.preventDefault();
$(this).siblings('input').val('').focus();
});
});
function restorePageNumber() {
var savedPageNumber = getCookie('material_regpageNumber');
location.reload(true);
}
</script>
<script>
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
if(loader)
loader.style.display = 'none';
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
$(".close").on("click", function() {
$("#myModal").hide();
});
$("#newBtn").on("click", function() {
loadForm('insert');
});
$("#searchBtn").on("click", function() {
$("#board_form").submit();
});
$("#closeBtn").on("click", function() {
var modal = document.getElementById("myModal");
modal.style.display = "none";
});
// upload
$("#uploadBtn").on("click", function() {
popupCenter('uploadgrid.php' , '업로드', 1800, 800);
});
$(document).off("click", ".view-import-inspection").on("click", ".view-import-inspection", function(event) {
// 부모 <tr> 요소의 data 속성에서 값을 가져옵니다.
var row = $(this).closest('tr');
var num = row.data('num');
var itemname = row.data('itemname');
var spec = row.data('specification');
var remarks = row.data('remarks');
// 클릭 이벤트 전파 방지
event.stopPropagation();
// viewBoardInstock 함수 호출
viewBoardInstock(num, itemname, spec, remarks);
});
});
function enter() {
$("#board_form").submit();
}
function inputNumberFormat(obj) {
obj.value = obj.value.replace(/[^0-9]/g, '');
let value = obj.value.replace(/,/g, '');
obj.value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
$(document).on("keypress", "input", function(event) {
return event.keyCode != 13;
});
$(document).ready(function(){
// 방문기록 남김
saveMenuLog('수입검사 관리대장');
});
</script>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/instock/common/viewJS.php'; ?> <!--공통 JS -->
</body>
</html>