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

765 lines
29 KiB
PHP

<?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';
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
$num = isset($_REQUEST["num"]) ? $_REQUEST["num"] : "";
$tablename = isset($_REQUEST["tablename"]) ? $_REQUEST["tablename"] : "";
$first_writer = '';
if ($mode === 'copy') {
$title_message = "(데이터복사) 절곡 BOM단가";
} else {
$title_message = "절곡 BOM단가";
}
?>
<link href="css/style.css?v=1" rel="stylesheet">
<title><?= $title_message ?></title>
</head>
<body>
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/mymodal.php';
// 첨부 이미지에 대한 부분
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
// 임시테이블
$tablename_tmp = 'price_bend';
try {
// 최신 데이터를 가져오기 위해 ORDER BY와 LIMIT을 추가
$sql = "SELECT * FROM {$DB}.$tablename_tmp where (is_deleted IS NULL or is_deleted = '0') ORDER BY num DESC LIMIT 1";
$stmh = $pdo->prepare($sql);
$stmh->execute();
$row = $stmh->fetch(PDO::FETCH_ASSOC); // $row 배열로 DB 정보를 불러온다.
$item_bend = $row['itemList'];
} catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
$today = date("Y-m-d"); // 현재일자 변수지정
if ($mode == "modify" || $mode == "view") {
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";
}
} catch (PDOException $Exception) {
print "오류: " . $Exception->getMessage();
}
}
if ($mode !== "modify" and $mode !== "copy" and $mode !== "view") {
include '_request.php';
$first_writer = $user_name;
$basicdate = $today;
}
if ($mode == "copy") {
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";
} catch (PDOException $Exception) {
print "오류: " . $Exception->getMessage();
}
// 자료번호 초기화
$num = 0;
// $basicdate = $today;
}
$unitList = isset($row['unitList']) ? $row['unitList'] : [];
// unitList가 문자열일 때만 json_decode 실행
if (is_string($unitList)) {
$unitList = json_decode($unitList, true);
}
// unitList가 유효한 배열이 아닐 경우 빈 배열로 초기화
if (!is_array($unitList)) {
$unitList = [];
}
?>
<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" value="<?= $num ?>">
<input type="hidden" id="level" name="level" value="<?= $level ?>">
<input type="hidden" id="user_name" name="user_name" value="<?= $user_name ?>">
<input type="hidden" id="update_log" name="update_log" value="<?= $update_log ?>">
<input type="hidden" id="tablename" name="tablename" value="<?= $tablename ?>">
<input type="hidden" id="unitList" name="unitList" value="">
<div class="container-fluid">
<div class="row d-flex justify-content-center align-items-center">
<div class="card align-middle" >
<div class="card-body text-center">
<div class="d-flex justify-content-center align-items-center mt-2 mb-2 p-2 m-2">
<h3><?= $title_message ?></h3>
&nbsp; &nbsp; &nbsp; &nbsp;
<?php if ($mode == 'view') { ?>
<button type="button" class="btn btn-dark btn-sm me-1"
onclick="location.href='write_form.php?mode=modify&num=<?= $num ?>&tablename=<?= $tablename ?>';">
<ion-icon name="color-wand-outline"></ion-icon> 수정
</button>
<?php } ?>
<?php if ($mode !== 'view') { ?>
<button id="saveBtn" class="btn btn-dark btn-sm me-1" type="button">
<?php if ((int)$num > 0) print ' <i class="bi bi-hdd-fill"></i> 저장'; else print ' <i class="bi bi-hdd-fill"></i> 저장'; ?>
</button>
<?php } if ($level == '1') { ?>
<?php if ($mode !== 'copy' && $mode !== 'modify') { ?>
<button id="copyBtn" class="btn btn-primary btn-sm me-1" type="button"><i
class="bi bi-copy"></i> 복사
</button>
<button id="deleteBtn" class="btn btn-danger btn-sm me-1" type="button"><i
class="bi bi-trash2"></i> 삭제
</button>
<?php } ?>
<button type="button" class="btn btn-outline-dark btn-sm me-1"
onclick="self.close();"><i class="bi bi-box-arrow-left"></i> 창닫기
</button> &nbsp;
<?php } ?>
</div>
<div class="d-flex p-1 mb-1 justify-content-center align-items-center">
<div class="table-responsive">
<table class="table table-bordered">
<thead class="table-primary">
<tr>
<th class="text-center w100px">작성 기준일</th>
<th class="text-center w120px">대분류</th>
<th class="text-center w140px">중분류</th>
<th class="text-center w140px">모델명</th>
<th class="text-center w250px">품목명</th>
<th class="text-center w100px">재질</th>
<th class="text-center w100px">단위</th>
<th class="text-center w50px">수량</th>
<th class="text-center w120px">산출단가/M</th>
<th class="text-center " style="width:450px;" >메모</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="date" name="basicdate" id="basicdate" class="form-control" value="<?= $basicdate ?>">
</td>
<td>
<select name="firstitem" id="firstitem" class="form-select mx-1 w100px" style="font-size: 0.8rem; height: 32px;">
<option value="" <?= ($firstitem === '') ? 'selected' : '' ?>>(대분류)</option>
<?php
$l1_list = getCategoryByName(); // 1단계 전체 이름 배열을 가져옴
foreach ($l1_list as $item) {
$selected = ($firstitem === $item) ? 'selected' : '';
echo '<option value="' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '" ' . $selected . '>' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '</option>';
}
?>
</select>
</td>
<td>
<?php
// 예: getCategoryByName($parentName) 함수가 존재하며,
// '절곡물'이라는 2단계 카테고리의 자식(3단계) 카테고리 이름 배열을 리턴한다.
$l3_list = getCategoryByName('스크린','절곡물');
?>
<select id="seconditem" name="seconditem" class="form-select w160px mx-1" style="font-size: 0.8rem; height: 32px;">
<option value="">(중분류)</option>
<?php foreach($l3_list as $itemVal): ?>
<option
value="<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>"
<?= ($seconditem === $itemVal) ? 'selected' : '' ?>>
<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<?php
// JSON 파일 경로 (예: /models/models.json)
$jsonFile = $_SERVER['DOCUMENT_ROOT'].'/models/models.json';
$modelsList = [];
if(file_exists($jsonFile)){
$jsonContent = file_get_contents($jsonFile);
$modelsList = json_decode($jsonContent, true);
if(!is_array($modelsList)) {
$modelsList = [];
}
}
// 기존 데이터가 있으면 기본 선택할 값
$selectedModel = isset($row['model_name']) ? $row['model_name'] : '';
// 대분류 선택값
$selectedMajor = isset($row['major_category']) ? $row['major_category'] : '';
?>
<select id="prodcode" name="prodcode" class="form-select mx-1 w100px" style="font-size: 0.8rem; height: 32px;">
<option value="">모델 선택</option>
<?php
// 초기 옵션: 대분류가 선택되어 있으면 해당 모델만 표시
foreach($modelsList as $model):
if($selectedMajor === '' || $model['slatitem'] === $selectedMajor):
?>
<option value="<?= htmlspecialchars($model['model_name'], ENT_QUOTES, 'UTF-8') ?>" <?= ($prodcode === $model['model_name']) ? 'selected' : '' ?>>
<?= htmlspecialchars($model['model_name'], ENT_QUOTES, 'UTF-8') ?>
</option>
<?php
endif;
endforeach;
?>
</select>
</td>
<td>
<input type="text" name="proditem" id="proditem" class="form-control" value="<?= $proditem ?>">
</td>
<td>
<select name="material" id="material"class="form-select mx-1 w100px" style="font-size: 0.8rem; height: 32px;">
<option value="SUS" <?= ($material == 'SUS') ? 'selected' : '' ?>>SUS</option>
<option value="EGI" <?= ($material == 'EGI') ? 'selected' : '' ?>>EGI</option>
</select>
</td>
<td>
<select name="unit" id="unit" class="form-select mx-1 w100px" style="font-size: 0.8rem; height: 32px;">
<option value="세트" <?= ($unit == '세트') ? 'selected' : '' ?>>세트</option>
<option value="EA" <?= ($unit == 'EA') ? 'selected' : '' ?>>EA</option>
</select>
</td>
<td>
<input type="text" name="su" id="su" class="form-control" value="<?= $su ?>">
</td>
<td>
<input type="text" name="unitprice" id="unitprice" class="form-control" value="<?= $unitprice ?>">
</td>
<td>
<input type="text" name="memo" id="memo" class="form-control text-start" placeholder="(메모)" value="<?= $memo ?>">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<?php if ($mode !== 'view') { ?>
<span class="form-control">
<div id="grid"></div>
</span>
<?php } else { ?>
<div class="d-flex justify-content-center align-items-center">
<table class="table" id="myTable">
<thead class="table-primary">
<tr>
<th class="text-center">번호</th>
<th class="text-center">품목명</th>
<th class="text-center w200px">품목번호</th>
<th class="text-center">마감 재질</th>
<th class="text-center">두께</th>
<th class="text-center">상수</th>
<th class="text-center">폭 (W)</th>
<th class="text-center">길이 (L)</th>
<th class="text-center">면적 (㎡)</th>
<th class="text-center">면적단가</th>
<th class="text-center">단위</th>
<th class="text-center">수량</th>
<th class="text-center">산출단가/M</th>
<th class="text-center">자동계산</th>
<th class="text-center w300px">폭 계산 산식</th>
</tr>
</thead>
<tbody>
<?php
$unitList = isset($row['unitList']) ? json_decode($row['unitList'], true) : [];
// $unitList가 유효한 배열인지 확인
if (is_array($unitList) && count($unitList) > 0) {
foreach ($unitList as $index => $item) {
?>
<tr>
<td class="text-center"><?= $index + 1 ?></td>
<td class="text-start"><?= htmlspecialchars($item['col1']) ?></td> <!-- 품목명 -->
<td class="text-start"><?= htmlspecialchars($item['col2']) ?></td> <!-- 품목번호 -->
<td class="text-center"><?= htmlspecialchars($item['col3']) ?></td> <!-- 재질 -->
<td class="text-center"><?= htmlspecialchars($item['col4']) ?></td> <!-- 두께 -->
<td class="text-center"><?= htmlspecialchars($item['col5']) ?></td> <!-- 상수 -->
<td class="text-center"><?= htmlspecialchars($item['col6']) ?></td> <!-- 폭 (W) -->
<td class="text-center"><?= htmlspecialchars($item['col7']) ?></td> <!-- 길이 (L) -->
<td class="text-center"><?= htmlspecialchars($item['col8']) ?></td> <!-- 면적 (㎡) -->
<td class="text-center"><?= htmlspecialchars($item['col9']) ?></td> <!-- 면적단가 -->
<td class="text-center"><?= htmlspecialchars($item['col10']) ?></td> <!-- 단위 -->
<td class="text-center"><?= htmlspecialchars($item['col11']) ?></td> <!-- 수량 -->
<td class="text-end"><?= htmlspecialchars($item['col12']) ?></td> <!-- 산출단가/M -->
<td class="text-center"><?= htmlspecialchars($item['col13']) ?></td>
<td class="text-start"><?= htmlspecialchars($item['col14']) ?></td>
</tr>
<?php
}
} else {
echo "<tr><td colspan='13' class='text-center'>No Data Available</td></tr>";
}
?>
</tbody>
</table>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</form>
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
});
var mode = '<?php echo $mode; ?>';
var ajaxRequest_write = null;
$(document).ready(function () {
var unitList = <?php echo json_encode($unitList); ?>;
var item_bend = <?php echo isset($item_bend) ? json_encode($item_bend) : '[]'; ?>;
if (typeof item_bend === 'string') {
try {
item_bend = JSON.parse(item_bend);
} catch (e) {
console.error('JSON 파싱 오류:', e);
item_bend = [];
}
}
if (!Array.isArray(item_bend)) {
item_bend = [];
}
console.log(item_bend); // col17은 면적당 단가를 의미함
// console.log(unitList);
let row_count = 20; // 최대 행 개수
const data = [];
for (let i = 0; i < row_count; i++) {
const row = {
col1: unitList[i] ? unitList[i].col1 : '', // 품목명
col2: unitList[i] ? unitList[i].col2 : '', // 품목번호
col3: unitList[i] ? unitList[i].col3 : '', // 재질
col4: unitList[i] ? unitList[i].col4 : '', // 두께
col5: unitList[i] ? unitList[i].col5 : '', // 상수
col6: unitList[i] ? unitList[i].col6 : '', // 폭 (W)
col7: unitList[i] ? unitList[i].col7 : '', // 길이 (L)
col8: unitList[i] ? unitList[i].col8 : '', // 면적 (㎡)
col9: unitList[i] ? unitList[i].col9 : '', // 면적단가
col10: unitList[i] ? unitList[i].col10 : '', // 단위
col11: unitList[i] ? unitList[i].col11 : '', // 수량
col12: unitList[i] ? unitList[i].col12 : '', // 산출단가/M
col13: unitList[i] ? unitList[i].col13 : '', // 자동계산
col14: unitList[i] ? unitList[i].col14 : '', // 산식
};
data.push(row);
}
const grid = new tui.Grid({
el: document.getElementById('grid'),
data: data,
bodyHeight: 600,
columns: [
{ header: '품목명', name: 'col1', editor: 'text', align: 'left', width: 250 },
{ header: '품목번호', name: 'col2', editor: 'text', align: 'center', width: 150 },
{ header: '재질', name: 'col3', editor: 'text', align: 'center' , width: 150 },
{ header: '두께', name: 'col4', editor: 'text', align: 'center', width: 100 },
{ header: '상수', name: 'col5', editor: 'text', align: 'center' , width: 60 },
{ header: '폭 (W)', name: 'col6', editor: 'text', align: 'center', width: 60 },
{ header: '길이 (L)', name: 'col7', editor: 'text', align: 'center' , width: 60 },
{ header: '면적 (㎡)', name: 'col8', editor: 'text', align: 'center' , width: 60 },
{ header: '면적단가', name: 'col9', editor: 'text', align: 'center' , width: 80 },
{ header: '단위', name: 'col10', editor: 'text', align: 'center', width: 50 },
{ header: '수량', name: 'col11', editor: 'text', align: 'center', width: 50 },
{ header: '산출단가/M', name: 'col12', editor: 'text', align: 'center' , width: 80 },
{ header: '자동계산', name: 'col13', editor: 'text', align: 'center', width: 60 },
{ header: '폭 계산 산식', name: 'col14', editor: 'text', align: 'left', width: 400 }
],
columnOptions: {
resizable: true
},
rowHeaders: ['rowNum']
});
// 그리드 값이 변경될 때마다 호출되는 함수
grid.on('afterChange', function (ev) {
applyMaterialPrice(); // 면적단가(col9) 자동 설정
updateGrid(); // 그리드 업데이트
calculateSum(); // 변경 후 합계를 계산
});
// 면적단가(col9) 자동 적용 함수
function applyMaterialPrice() {
const rowCount = grid.getRowCount();
for (let i = 0; i < rowCount; i++) {
const m2 = grid.getValue(i, 'col8') || 0; ; // 면적
let material = grid.getValue(i, 'col3') // 재질
.replace(/T/gi, '') // 'T' 또는 't' 제거
.toUpperCase(); // 대문자로 변환
// 특정 숫자 변환
material = material.replace(/\b1\.15\b/g, '1.2').replace(/\b1\.55\b/g, '1.6'); // 1.15를 1.2로 수정, 1.55를 1.6으로 수정하는 로직
// console.log(material);
if(m2 > 0) // 면적이 0이 아닐때
{
// col1 + col5 조합으로 item_bend에서 col17 값을 찾아 col9에 적용 // 절곡가격 형태 가져오기
const matchingItem = item_bend.find(item => {
return item.col1 + ' ' + item.col5 === material
});
if (matchingItem) {
// 일치하는 아이템이 있으면 col17(면적단가) 값을 col9에 설정 (면적단가)
grid.setValue(i, 'col9', matchingItem.col17);
} else {
// 일치하는 아이템이 없으면 기본값 0으로 설정
grid.setValue(i, 'col9', '');
}
}
}
}
// 자동계산 로직 포함
function updateGrid() {
const rowCount = grid.getRowCount();
for (let i = 0; i < rowCount; i++) {
const col13Value = parseInt(grid.getValue(i, 'col13')) || 0; // 자동계산 플래그 확인
if (col13Value === 1) {
// 산출단가 계산
const width = parseFloat(grid.getValue(i, 'col6').replace(/,/g, '')) || 0; // 폭
const length = parseFloat(grid.getValue(i, 'col7').replace(/,/g, '')) || 0; // 길이
const areaPrice = parseFloat(grid.getValue(i, 'col9').replace(/,/g, '')) || 0; // 면적단가
const quantity = parseFloat(grid.getValue(i, 'col11').replace(/,/g, '')) || 0; // 수량
const area = ((width * length) / 1000000).toFixed(2); // 면적계산 소수점 둘째자리까지 계산
let unitPrice = (area * areaPrice * quantity).toFixed(0); // 산출단가 계산 소수점 없애기
unitPrice = Number(unitPrice); // 숫자로 변환
console.log('unitPrice.toLocaleString()', unitPrice.toLocaleString());
// 계산된 값 콤마 추가하여 표시
grid.setValue(i, 'col12', unitPrice.toLocaleString());
// 상수 계산
const material = grid.getValue(i, 'col3').toUpperCase(); // 대문자로 변환하여 비교
if (material.includes('EGI')) {
grid.setValue(i, 'col5', '7.89');
} else if (material.includes('SUS')) {
grid.setValue(i, 'col5', '7.93');
} else {
grid.setValue(i, 'col5', ''); // 기본값으로 상수 제거
}
// 면적 계산값도 반영
grid.setValue(i, 'col8', area.toLocaleString());
}
}
}
// 합계 계산 함수
function calculateSum() {
let total = 0;
const rowCount = grid.getRowCount();
for (let i = 0; i < rowCount; i++) {
let col13Value = grid.getValue(i, 'col13') || '0';
let col12Value = grid.getValue(i, 'col12') || '0';
// 콤마 제거 후 숫자로 변환
col13Value = parseFloat(col13Value.replace(/,/g, '')) || 0;
col12Value = parseFloat(col12Value.replace(/,/g, '')) || 0;
// 소수점 첫째자리에서 반올림
col12Value = Math.round(col12Value * 10) / 10;
// 합계에 추가
if(Number(col13Value )>0)
total += col12Value;
}
// 합계를 unitprice에 동적으로 반영 (콤마 추가하여 표시)
document.getElementById('unitprice').value = total.toLocaleString();
}
// 저장 버튼 클릭 시 데이터를 JSON으로 변환 후 숨겨진 input에 저장
$("#saveBtn").click(function () {
saveGridData();
});
function saveGridData() {
let unitList = [];
const rowCount = grid.getRowCount();
for (let i = 0; i < rowCount; i++) {
unitList.push({
col1: grid.getValue(i, 'col1'),
col2: grid.getValue(i, 'col2'),
col3: grid.getValue(i, 'col3'),
col4: grid.getValue(i, 'col4'),
col5: grid.getValue(i, 'col5'),
col6: grid.getValue(i, 'col6'),
col7: grid.getValue(i, 'col7'),
col8: grid.getValue(i, 'col8'),
col9: grid.getValue(i, 'col9'),
col10: grid.getValue(i, 'col10'),
col11: grid.getValue(i, 'col11'),
col12: grid.getValue(i, 'col12'),
col13: grid.getValue(i, 'col13'),
col14: grid.getValue(i, 'col14'),
});
}
// 저장된 데이터를 hidden input에 넣음
document.getElementById('unitList').value = JSON.stringify(unitList);
// 폼 데이터 저장
saveData();
}
function saveData() {
var form = $('#board_form')[0];
var formData = new FormData(form);
showMsgModal(2); // 파일저장중
$.ajax({
url: "insert.php",
type: "post",
data: formData,
processData: false,
contentType: false,
success: function (data) {
// console.log(data);
$(opener.location).attr("href", "javascript:restorePageNumber();");
setTimeout(function() {
hideMsgModal();
Toastify({
text: "저장완료",
duration: 3000,
close: true,
gravity: "top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
hideOverlay();
self.close();
}, 2000);
},
error: function (jqxhr, status, error) {
console.log(jqxhr, status, error);
}
});
}
// 조회 모드일 때 필드 비활성화
if ('<?php echo $mode; ?>' === 'view') {
grid.disable();
}
});
var dataTable; // DataTables 인스턴스 전역 변수
var bendingfeepageNumber; // 현재 페이지 번호 저장을 위한 전역 변수
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('bendingfeepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
// 페이지 변경 이벤트 리스너
dataTable.on('page.dt', function() {
var bendingfeepageNumber = dataTable.page.info().page + 1;
setCookie('bendingfeepageNumber', bendingfeepageNumber, 10); // 쿠키에 페이지 번호 저장
});
// 페이지 길이 셀렉트 박스 변경 이벤트 처리
$('#myTable_length select').on('change', function() {
var selectedValue = $(this).val();
dataTable.page.len(selectedValue).draw(); // 페이지 길이 변경 (DataTable 파괴 및 재초기화 없이)
// 변경 후 현재 페이지 번호 복원
savedPageNumber = getCookie('bendingfeepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
});
});
function restorePageNumber() {
var savedPageNumber = getCookie('bendingfeepageNumber');
location.reload(true);
}
$(document).ready(function(){
$("#copyBtn").click(function(){
location.href = 'write_form.php?mode=copy&num=' + $("#num").val() + "&tablename=" + $("#tablename").val() ;
}); // end of function
// 삭제버튼
$("#deleteBtn").click( function() {
var update_log = $("#update_log").val();
var user_name = $("#user_name").val();
var level = $("#level").val();
if (!update_log.includes(user_name) && level !== '1')
{
Swal.fire({
title: '삭제불가',
text: "작성자와 관리자만 삭제가능합니다.",
icon: 'error',
confirmButtonText: '확인'
});
} else {
Swal.fire({
title: '자료 삭제',
text: "삭제는 신중! 정말 삭제하시겠습니까?",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '삭제',
cancelButtonText: '취소'
}).then((result) => {
if (result.isConfirmed) {
$("#mode").val('delete'); // `mode` 값을 설정
var form = $('#board_form')[0];
var formData = new FormData(form); // `formData`를 여기에서 정의합니다.
// `formData`에 필요한 추가 데이터를 수동으로 설정
formData.set('mode', $("#mode").val());
formData.set('num', $("#num").val());
console.log('mode', $("#mode").val());
console.log('num', $("#num").val());
if ( (typeof ajaxRequest_write !== 'undefined' && ajaxRequest_write) || ajaxRequest_write!==null ) {
ajaxRequest_write.abort();
}
ajaxRequest_write = $.ajax({
enctype: 'multipart/form-data', // file을 서버에 전송하려면 이렇게 해야 함 주의
processData: false,
contentType: false,
cache: false,
timeout: 1000000,
url: "insert.php",
type: "post",
data: formData,
dataType: "json",
success : function( data ){
console.log(data);
Toastify({
text: "파일 삭제완료 ",
duration: 2000,
close:true,
gravity:"top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
setTimeout(function(){
if (window.opener && !window.opener.closed) {
// 부모 창에 restorePageNumber 함수가 있는지 확인
if (typeof window.opener.restorePageNumber === 'function') {
window.opener.restorePageNumber(); // 함수가 있으면 실행
}
// window.opener.location.reload(); // 부모 창 새로고침
window.close();
}
}, 2000);
},
error : function( jqxhr , status , error ){
console.log( jqxhr , status , error );
}
});
}
});
}
});
// 화면이 시작된 후
hideOverlay();
});
// mode == 'view' 조회 화면일때 사용금지 시키는 구문 -->
$(document).ready(function(){
var mode = '<?php echo $mode; ?>';
// 마지막에 넣어줘야 전체를 적용할 수 있다.
if (mode === 'view') {
$('input, textarea, select').prop('disabled', true); // Disable all input, textarea, and select elements
$('input[type=file]').prop('disabled', false);
$('input[type=hidden]').prop('disabled', false);
}
});
</script>
</body>
</html>