Files
sam-kd/estimate/edit.php

680 lines
22 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;
}
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
// POST 요청으로 전달된 데이터 받기
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
$num = isset($_REQUEST['num']) ? $_REQUEST['num'] : '';
$tablename = isset($_REQUEST['tablename']) ? $_REQUEST['tablename'] : 'output';
$header = isset($_REQUEST['header']) ? $_REQUEST['header'] : '';
$title_message = "스크린 발주 등록/수정";
$authorities = ["개발자","전진","노완호","이세희","함신옥","손금주","이은진","이경호"];
// print $user_id;
// 발주서에서 견적서를 불러와서 편집할때 나오는 화면임
// 발주서에서 견적서를 불러와서 편집할때 나오는 화면임
?>
<title> <?=$title_message?> </title>
<style>
textarea {
overflow: hidden;
resize: none; /* 사용자 크기 조절을 방지 */
}
/* 기본 스타일 설정 */
input[type="checkbox"],
input[type="radio"] {
transform: scale(1.5); /* 크기 확대 */
margin: 3px; /* 여백 추가 */
}
/* "readonly" 상태일 때 스타일 설정 */
.readonly-checkbox,
.readonly-radio {
pointer-events: none; /* 사용자 상호작용 비활성화 */
opacity: 1; /* 불투명도 설정 */
color: red;
}
/* 레이블 텍스트 크게 설정 */
label {
font-size: 1.5em; /* 글꼴 크기 확대 */
display: inline-block;
margin: 3px 0;
}
.w-40{
width: 40%!important;
}
.w-50{
width: 50%!important;
}
.w-60{
width: 60%!important;
}
.viewNoBtn {
cursor : pointer;
}
</style>
</head>
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/mymodal.php';
// 첨부 이미지에 대한 부분
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
$today = date("Y-m-d"); // 현재일자 변수지정
$num = $_GET['num'] ?? '';
$tempKey = $_GET['tempKey'] ?? '';
if ($tempKey) {
$jsonFilePath = $_SERVER['DOCUMENT_ROOT'] . '/output/json/' . $tempKey . '.json';
// JSON 파일이 존재하면 읽어옴
if (file_exists($jsonFilePath)) {
$jsonData = file_get_contents($jsonFilePath);
$estimateList = json_decode($jsonData, true);
} else {
echo "JSON 파일을 찾을 수 없습니다.";
exit;
}
} else {
echo "유효하지 않은 접근입니다.";
exit;
}
if (empty($makeWidth)) $makeWidth = '160';
if (empty($makeHeight)) $makeHeight = '350';
if (empty($maguriWing)) $maguriWing = '50';
if (empty($inspectionFeeFormatted)) $inspectionFeeFormatted = '50,000';
?>
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data" >
<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="level" name="level" value="<?= isset($level) ? $level : '' ?>">
<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="header" name="header" value="<?= isset($header) ? $header : '' ?>">
<input type="hidden" id="is_deleted" name="is_deleted" value="<?= isset($is_deleted) ? $is_deleted : '0' ?>">
<input type="hidden" id="screenorslat" name="screenorslat"> <!-- 라디오버튼 저장하려면 두개의 변수가 필요하다. -->
<input type="hidden" id="estimateList" name="estimateList">
<div class="container">
<div class="row justify-content-center align-items-center ">
<div class="card align-middle " style="width: 55rem;">
<div class="card-body text-center">
<div class="row d-flex justify-content-center align-items-center mb-3" >
<div class="col-sm-1" >
<div class="d-flex p-1 mb-1 justify-content-start align-items-center ">
<?=$mode?>
</div>
</div>
<div class="col-sm-9" >
<div class="d-flex p-1 mb-1 justify-content-center align-items-center ">
<h3> <?=$title_message?> </h3> &nbsp; &nbsp; &nbsp; &nbsp;
<button id="saveBtn" class="btn btn-dark btn-sm me-1 " type="button"> <i class="bi bi-hdd-fill"></i> 발주서에 적용하기 </button>
</div>
</div>
<div class="col-sm-2" >
<button type="button" class="btn btn-outline-dark btn-sm " onclick="self.close();" > <i class="bi bi-box-arrow-left"></i> 창닫기 </button> &nbsp;
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid" >
<div id="ScreenSection" >
<div class="row">
<div class="col-sm-2">
<div class="d-flex justify-content-end mt-2">
<button type='button' id='view_screenguidebookBtn' class='btn btn-secondary btn-sm ms-2 me-3 mt-1'> <i class='bi bi-chevron-down'></i> </button>
</div>
</div>
<div class="col-sm-10">
<div id="view_screenguidebook">
<div class="d-flex row justify-content-start mt-2">
<table class="table table-bordered w-75">
<thead class="table-secondary">
<tr>
<th>상품명</th>
<th>제품명</th>
<th>제품명 설명</th>
<th>비고</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-start">국민방화 스크린 셔터</td>
<td class="text-start">KSS01</td>
<td class="text-start">K(경동:국민방화 브랜드명) S(실리카코팅직물 스크린) S(SUS마감)</td>
<td class="text-start"></td>
</tr>
<tr>
<td class="text-start">국민방화 스크린 셔터</td>
<td class="text-start">KSS02</td>
<td class="text-start">K(경동:국민방화 브랜드명) S(실리카코팅직물 스크린) S(SUS마감)</td>
<td class="text-start"></td>
</tr>
<tr>
<td class="text-start">국민방화 스크린 셔터</td>
<td class="text-start">KSE01</td>
<td class="text-start">K(경동:국민방화 브랜드명) S(실리카코팅직물 스크린) E(EGI마감)</td>
<td class="text-start"></td>
</tr>
<tr>
<td class="text-start">국민방화 스크린 플러스 셔터</td>
<td class="text-start">KWE01</td>
<td class="text-start">K(경동:국민방화 브랜드명) W(와이어글라스코팅직물 스크린) E(EGI마감)</td>
<td class="text-start">SUS 마감일 경우 --- 기존 EGI 마감재에 SUS 마감재로 덧방 추가</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="d-flex justify-content-center align-items-center">
<span class="text-dark fs-6 me-4"> 공통 제작치수 적용 </span>
<span class="text-primary fs-6 mx-1"> 가로() </span>
<input type="text" id="makeWidth" name="makeWidth" value="<?php echo htmlspecialchars($makeWidth); ?>" class="form-control text-primary fs-6 w60px me-2">
<span class="text-danger fs-6 mx-1"> 세로(높이) </span>
<input type="text" id="makeHeight" name="makeHeight" value="<?php echo htmlspecialchars($makeHeight); ?>" class="form-control text-danger fs-6 w60px">
<span class="text-success fs-6 ms-4 me-1"> 마구리 날개치수 </span>
<input type="text" id="maguriWing" name="maguriWing" value="<?php echo htmlspecialchars($maguriWing); ?>" class="form-control text-success fs-6 w60px">
<span class="text-dark fs-6 ms-4 me-1"> 검사비 설정 </span>
<input type="text"
id="inspectionFee"
name="inspectionFee"
value="<?php echo htmlspecialchars($inspectionFeeFormatted); ?>"
class="form-control text-dark text-end fs-6 w80px col-input"
onclick="this.select();"
oninput="inputNumberFormat(this);">
<span class="text-secondary fs-6 ms-5 me-1"> 값을 설정하고 행을 추가해 주세요. 값이 반영됩니다. </span>
</div>
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/estimate/common/common_screen.php'; // 견적서에서 screen 화면 테이블 공통부분
// 스크린셔터
generateTableSection('estimate', '스크린셔터', $badgeClass = 'bg-primary', $user_id, '발주서', $mode);
?>
</div>
</div>
</div>
</form>
<script>
const authorities = <?php echo json_encode($authorities, JSON_UNESCAPED_UNICODE); ?>;
// console.log(authorities); // 배열 출력
function isZeroOrEmpty(value) {
return value === '0' || value === '';
}
function captureReturnKey(e) {
if(e.keyCode==13 && e.srcElement.type != 'textarea')
return false;
}
</script>
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
if(loader)
loader.style.display = 'none';
});
</script>
<script>
var mode = '<?php echo $mode; ?>';
var ajaxRequest_write = null;
</script>
<script>
var dataTable; // DataTables 인스턴스 전역 변수
var outputpageNumber; // 현재 페이지 번호 저장을 위한 전역 변수
var ajaxRequest_write = null;
$(document).ready(function() {
// DataTables 초기 설정
dataTable = $('#myTable').DataTable({
"paging": true,
"ordering": true,
"searching": true,
"pageLength": 500,
"lengthMenu": [25, 50, 100, 200, 500, 1000],
"language": {
"lengthMenu": "Show _MENU_ entries",
"search": "Live Search:"
},
"order": [[0, 'asc']]
});
// 페이지 번호 복원 (초기 로드 시)
var savedPageNumber = getCookie('estimatepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
// 페이지 변경 이벤트 리스너
dataTable.on('page.dt', function() {
var estimatepageNumber = dataTable.page.info().page + 1;
setCookie('estimatepageNumber', estimatepageNumber, 10); // 쿠키에 페이지 번호 저장
});
// 페이지 길이 셀렉트 박스 변경 이벤트 처리
$('#myTable_length select').on('change', function() {
var selectedValue = $(this).val();
dataTable.page.len(selectedValue).draw(); // 페이지 길이 변경 (DataTable 파괴 및 재초기화 없이)
// 변경 후 현재 페이지 번호 복원
savedPageNumber = getCookie('estimatepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
});
});
function restorePageNumber() {
var savedPageNumber = getCookie('estimatepageNumber');
// if (savedPageNumber) {
// dataTable.page(parseInt(savedPageNumber) - 1).draw('page');
// }
location.reload(true);
}
// 팝업 창에서 데이터 저장 및 부모 창에 전달
function saveData() {
const myform = document.getElementById('board_form');
let allValid = true;
// 유효성 검사 실패 시 리턴
if (!allValid) return;
var num = $("#num").val();
$("#overlay").show();
$("button").prop("disabled", true);
Toastify({
text: "발주서에 적용중...",
duration: 2000,
close: true,
gravity: "top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
// estimateTable의 데이터를 JSON으로 직렬화
let formData = [];
$('#estimateTable tbody tr').each(function() {
let rowData = {};
$(this).find('input, select').each(function() {
let name = $(this).attr('name').replace('[]', '');
let value = $(this).val();
rowData[name] = value;
});
formData.push(rowData);
});
let jsonString = JSON.stringify(formData);
$('#estimateList').val(jsonString);
// 부모 창에 데이터를 전달
if (window.opener && !window.opener.closed) {
// 부모 창의 숨겨진 필드 estimateList에 데이터 저장
window.opener.document.getElementById('estimateList').value = jsonString;
// makeWidth 필드 값 저장
window.opener.document.getElementById('makeWidth').value = $("#makeWidth").val();
// makeHeight 필드 값 저장
window.opener.document.getElementById('makeHeight').value = $("#makeHeight").val();
// maguriWing 필드 값 저장
window.opener.document.getElementById('maguriWing').value = $("#maguriWing").val();
// inspectionFee 필드 값 저장
window.opener.document.getElementById('inspectionFee').value = $("#inspectionFee").val();
// JSON 문자열을 배열로 파싱하여 부모 창에 전달
const parsedData = JSON.parse(jsonString); // 파싱된 배열 전달
window.opener.renderEstimateData({ estimateList: parsedData }, "reload" ); // reload 인수를 전달해서 새로 읽어 들인다.
} else {
alert('부모창을 찾을 수 없습니다.');
return;
}
// 일정 시간 후 창을 닫음
setTimeout(function() {
window.close();
}, 1000);
}
</script>
<script>
var ajaxRequest = null;
var ajaxRequest_write = null;
$(document).ready(function() {
initializePage();
bindEventHandlers();
$("#saveBtn").click(function() {
saveData();
});
});
// 초기 페이지 설정
function initializePage() {
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
var estimate = <?php echo json_encode($estimateList ?? []); ?>;
console.log(estimate);
loadTableData('#estimateTable', estimate, 'estimate');
}
// 이벤트 핸들러 바인딩
function bindEventHandlers() {
$(document).on('click', '.remove-row', function() {
var currentRow = $(this).closest('tr');
var tableBody = currentRow.closest('tbody');
// 현재 행 제거
currentRow.remove();
// 남아있는 행들의 col1 값을 다시 정렬
tableBody.children('tr').each(function(index) {
$(this).find('input[name="col1[]"]').val(index + 1);
});
updateTotals();
});
$(document).on('click', '.close-modal', function() {
$(this).closest('.modal').modal('hide');
});
$(document).on('click', '.add-row', function() {
var tableId = $(this).data('table');
var tableBody = $('#' + tableId).find('tbody');
addRow(tableBody, {}, tableId);
updateTotals();
});
// 행 복사
$(document).on('click', '.copy-row', function() {
if (mode !== 'view') {
var currentRow = $(this).closest('tr');
var tableBody = currentRow.closest('tbody');
var clonedRow = currentRow.clone(true); // true로 이벤트와 데이터를 복사
// 전체 행 수를 기준으로 새로운 col1 값 설정
var newCol1Value = tableBody.children('tr').length + 1;
clonedRow.find('input').each(function(index) {
var currentInput = currentRow.find('input').eq(index);
// col1 값이 있는 필드인 경우, 새로 계산된 값 설정
if ($(this).attr('name') === 'col1[]') {
$(this).val(newCol1Value);
} else {
// 나머지 필드는 그대로 복사
$(this).val(currentInput.val());
}
});
// 현재 행 바로 아래에 추가
currentRow.after(clonedRow);
}
updateTotals();
});
// 철재스라트 처리부분
$(document).on('click', '.remove-row_slat', function() {
$(this).closest('tr').remove();
slat_updateTotals();
});
$(document).on('click', '.add-row_slat', function() {
var tableId = $(this).data('table');
var tableBody = $('#' + tableId).find('tbody');
// addRow(tableBody, {}, tableId);
slat_updateTotals();
});
}
function loadTableData(tableId, dataList, typebutton) {
var tableBody = $(tableId).find('tbody');
var theadId;
switch (tableId) {
case '#estimateTable':
theadId = '#thead_estimate';
break;
case '#estimateSlatTable':
theadId = '#thead_estimateSlat';
break;
default:
theadId = null;
}
if (typeof dataList === 'string') {
try {
dataList = JSON.parse(dataList);
} catch (e) {
console.error('Failed to parse dataList:', e);
dataList = [];
}
}
$(theadId).show();
if (!Array.isArray(dataList)) {
dataList = [];
}
switch (tableId) {
case '#estimateTable':
if (dataList.length === 0) {
console.log('no record');
// $("#estimate_screenDiv").hide(); // 데이터가 없을 경우 div 숨기기
// 빈칸 만들기
addRow(tableBody, '', '');
} else {
dataList.forEach(function(item) {
addRow(tableBody, item, typebutton);
});
$("#estimate_screenDiv").show();
}
break;
case '#estimateSlatTable':
if (dataList.length === 0) {
console.log('no record');
// $("#estimate_slatDiv").hide(); // 데이터가 없을 경우 div 숨기기
addRow_slat(tableBody, '', '');
} else {
dataList.forEach(function(item) {
addRow_slat(tableBody, item, typebutton);
});
$("#estimate_slatDiv").show();
}
break;
default:
theadId = null;
}
}
function showModal(options, modalId, modalBodyId, input) {
targetInput = input;
$(modalBodyId).empty();
options.forEach(function(item) {
$(modalBodyId).append('<tr><td class="text-center">' + item + '</td></tr>');
});
$(modalId).modal('show');
}
function disableInputsForViewMode() {
$('input, textarea').prop('readonly', true);
$('select, .restrictbtn, .sub_add, .add').prop('disabled', true);
$('input[type=file]').prop('readonly', false);
$('input[type=checkbox]').prop('disabled', true);
$('.viewNoBtn').prop('disabled', true);
$('.specialbtnClear').prop('disabled', true);
}
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 closePopup() {
if (popupWindow && !popupWindow.closed) {
popupWindow.close();
isWindowOpen = false;
}
}
function showWarningModal() {
Swal.fire({
title: '등록 오류 알림',
text: '필수입력 요소를 확인바랍니다.',
icon: 'warning',
}).then(result => {
if (result.isConfirmed) {
return;
}
});
}
function showlotError() {
Swal.fire({
title: '등록 오류 알림',
text: '입력 항목들을 점검해주세요.',
icon: 'warning',
}).then(result => {
if (result.isConfirmed) {
return;
}
});
}
function inputNumber(input) {
// 현재 커서 위치를 저장
const cursorPosition = input.selectionStart;
// 입력값에서 숫자만 남기고 제거
const value = input.value.replace(/,/g, '');
// 천 단위 콤마 추가
const formattedValue = Number(value).toLocaleString();
// 포맷팅된 값으로 설정
input.value = formattedValue;
// 포맷팅 후에도 원래 커서 위치 유지
input.setSelectionRange(cursorPosition, cursorPosition);
}
$(document).ready(function() {
var estimate = <?php echo json_encode($estimateList ?? []); ?>;
});
$(document).ready(function() {
// 뷰 ID와 쿠키 이름 매핑 (output-list 제거)
var views = [
{ id: "estimate_screenDiv", cookie: "showEsimateScreenView", button: "#estimateScreen_view" , status : "block" },
{ id: "view_screenguidebook", cookie: "showEsimateScreenDetailView", button: "#view_screenguidebookBtn" , status : "none" },
{ id: "estimate_slatDiv", cookie: "showEsimateslatView", button: "#estimateslat_view", status : "block" },
{ id: "view_slatguidebook", cookie: "showEsimateslatDetailView", button: "#view_slatguidebookBtn", status : "none" }
];
// 각 뷰 버튼에 클릭 이벤트 할당 및 페이지 로드 시 초기화
views.forEach(function(view) {
// 버튼 클릭 시 View 토글
$(view.button).on("click", function() {
toggleView(view.id, view.cookie);
});
// 페이지 로드 시 View 초기화
initializeView(view.id, view.cookie, view.status); // 추가 초기상태도 전달한다.
});
});
// 공통 함수: View 토글 및 쿠키 설정
function toggleView(viewId, cookieName) {
var view = getCookie(cookieName);
var listContainer = $("#" + viewId);
if (view === "show") {
listContainer.css("display", "none");
setCookie(cookieName, "hide", 10);
} else {
listContainer.css("display", "block");
setCookie(cookieName, "show", 10);
}
}
// 공통 함수: 페이지 로드 시 쿠키를 기반으로 각 요소의 표시 상태 설정
function initializeView(viewId, cookieName, status) {
var view = getCookie(cookieName);
var listContainer = $("#" + viewId);
if (view === "show") {
listContainer.css("display", status);
} else {
listContainer.css("display", status); // 항상열리게 하려면 여기서 조정한다.
// listContainer.css("display", "none");
}
}
</script>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/estimate/common/common_addrowJS.php'; // 견적서에서 screen or slat JS코드 공통 ?>
</body>
</html>