초기 커밋: 5130 레거시 시스템

- URL 하드코딩 → .env APP_URL 기반 동적 URL로 변경
- DB 연결 하드코딩 → .env 기반으로 변경
- MySQL strict mode DATE 오류 수정
This commit is contained in:
2025-12-10 20:14:31 +09:00
commit aca1767eb9
6728 changed files with 1863265 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
<?php
$num = isset($_REQUEST['num']) ? $_REQUEST['num'] : '';
$is_deleted = isset($_REQUEST['is_deleted']) ? $_REQUEST['is_deleted'] : '';
$basicdate = isset($_REQUEST['basicdate']) ? $_REQUEST['basicdate'] : '';
$firstitem = isset($_REQUEST['firstitem']) ? $_REQUEST['firstitem'] : '';
$seconditem = isset($_REQUEST['seconditem']) ? $_REQUEST['seconditem'] : '';
$prodcode = isset($_REQUEST['prodcode']) ? $_REQUEST['prodcode'] : '';
$proditem = isset($_REQUEST['proditem']) ? $_REQUEST['proditem'] : '';
$material = isset($_REQUEST['material']) ? $_REQUEST['material'] : '';
$itemcode = isset($_REQUEST['itemcode']) ? $_REQUEST['itemcode'] : '';
$unit = isset($_REQUEST['unit']) ? $_REQUEST['unit'] : '';
$su = isset($_REQUEST['su']) ? $_REQUEST['su'] : '1';
$unitprice = isset($_REQUEST['unitprice']) ? $_REQUEST['unitprice'] : '';
$update_log = isset($_REQUEST['update_log']) ? $_REQUEST['update_log'] : '';
$searchtag = isset($_REQUEST['searchtag']) ? $_REQUEST['searchtag'] : '';
$unitList = isset($_REQUEST['unitList']) ? $_REQUEST['unitList'] : '{}' ;
$memo = isset($_REQUEST['memo']) ? $_REQUEST['memo'] : '' ;
?>

View File

@@ -0,0 +1,18 @@
<?php
$num = isset($row['num']) ? $row['num'] : '';
$is_deleted = isset($row['is_deleted']) ? $row['is_deleted'] : '';
$basicdate = isset($row['basicdate']) ? $row['basicdate'] : '';
$firstitem = isset($row['firstitem']) ? $row['firstitem'] : '';
$seconditem = isset($row['seconditem']) ? $row['seconditem'] : '';
$prodcode = isset($row['prodcode']) ? $row['prodcode'] : '';
$proditem = isset($row['proditem']) ? $row['proditem'] : '';
$material = isset($row['material']) ? $row['material'] : '';
$itemcode = isset($row['itemcode']) ? $row['itemcode'] : '';
$unit = isset($row['unit']) ? $row['unit'] : '';
$su = isset($row['su']) ? $row['su'] : '1';
$unitprice = isset($row['unitprice']) ? $row['unitprice'] : '';
$update_log = isset($row['update_log']) ? $row['update_log'] : '';
$searchtag = isset($row['searchtag']) ? $row['searchtag'] : '';
$unitList = isset($row['unitList']) ? $row['unitList'] : [] ;
$memo = isset($row['memo']) ? $row['memo'] : '' ;
?>

View File

@@ -0,0 +1,255 @@
@CHARSET "UTF-8";
@media print {
#Head {display:none;}
div.manage{display:none;}
div.bottom{display:none;}
div.segmental{margin-top:0px;}
div.composition{margin-top:0px;}
}
@media print{@page {size: portrait}}
@page {
size: portrait;
page-break-after: always;
counter-increment: page;
@top-center {
content: "Headline, yo!"
}
@bottom-right {
counter-increment: page;
content: "Page " counter(page);
}
}
.table, td, input {
font-size: 13px !important;
vertical-align: middle;
padding: 2px; /* 셀 내부 여백을 5px로 설정 */
border-spacing: 2px; /* 셀 간 간격을 5px로 설정 */
text-align:center;
}
.table td input.form-control, textarea.form-control {
height: 25px;
border: 1px solid #392f31; /* 테두리 스타일 추가 */
border-radius: 4px; /* 테두리 라운드 처리 */
}
input[type="checkbox"] {
transform: scale(1.6); /* 크기를 1.5배로 확대 */
margin-right: 10px; /* 확대 후의 여백 조정 */
}
table tr td {
vertical-align: middle;
}
@keyframes marquee {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
/*
#movingText {
display: inline-block;
overflow: hidden;
white-space: nowrap;
animation: marquee 20s linear infinite;
}
*/
/* Light mode styles */
body {
background-color: #ffffff;
color: #000000;
}
/* Dark mode styles */
[data-theme="dark"] {
background-color: #000000;
color: #ffffff;
}
/* Toggle switch styles */
.toggle-switch {
display: inline-block;
position: relative;
width: 60px;
height: 34px;
}
.toggle-switch input[type="checkbox"] {
display: none;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input[type="checkbox"]:checked + .toggle-slider {
background-color: #2196F3;
}
input[type="checkbox"]:checked + .toggle-slider:before {
transform: translateX(26px);
}
/* Sidebar hide button styles */
.sidebar-hide {
/* Your styles for the sidebar hide button */
}
.hidden-field {
display: none; /* 체크박스 체크 시 숨겨진 필드를 숨김 */
}
.part-field {
display: none; /* 체크박스 체크 시 숨겨진 필드를 숨김 */
}
/* 기본적으로 숨김 처리 */
#movingTextContainer {
cursor: pointer;
}
#autocomplete-list {
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
position: absolute;
top: 93%;
left: 50%;
right: 30%;
width : 10%;
z-index: 999;
}
.autocomplete-item {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-item:hover {
background-color: #e9e9e9;
}
.custom-tooltip {
display: none;
position: absolute;
border: 1px solid #ddd;
background-color: blue;
color:white;
font-size:25px;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
z-index: 1000;
top : 100;
}
/* 툴팁 위치 조정 */
#denkriModel:hover + .custom-tooltip {
display: block;
left: 70%; /* 화면 가로축의 중앙에 위치 */
top: 90px; /* Y축은 절대 좌표에 따라 설정 */
transform: translateX(-50%); /* 자신의 너비의 반만큼 왼쪽으로 이동 */
}
#showalign {
display: inline-block;
position: relative;
}
#showalignframe {
display: none;
position: absolute;
width: 400px;
z-index: 1000;
left: 50%; /* 화면 가로축의 중앙에 위치 */
transform: translateX(-40%); /* 자신의 너비의 반만큼 왼쪽으로 이동 */
}
#showextract {
display: inline-block;
position: relative;
}
#showextractframe {
display: none;
position: absolute;
width: 20%;
z-index: 1000;
left: 50%; /* 화면 가로축의 중앙에 위치 */
transform: translateX(-40%); /* 자신의 너비의 반만큼 왼쪽으로 이동 */
}
#showstatus {
display: inline-block;
position: relative;
}
#showstatusframe {
display: none;
position: absolute;
width: 40%;
z-index: 1000;
left: 50%; /* 화면 가로축의 중앙에 위치 */
transform: translateX(-40%); /* 자신의 너비의 반만큼 왼쪽으로 이동 */
}
/*
#showstatus {
display: inline-block;
position: relative;
}
#showstatusframe {
display: none;
position: absolute;
width: 30%;
max-height: 60px;
overflow-y: auto; /* Allow vertical scrolling if needed
z-index: 1000;
left: 50%;
bottom: 10%;
transform: translateX(-20%);
}
*/
th, td {
vertical-align: middle !important;
}
/* 토스트 컨테이너의 너비와 높이를 늘리는 예시 */
@media (max-width: 534px) { /* 부트스트랩의 기본 모바일 장치 너비 */
.toast {
width: 500px; /* 원하는 너비 */
height: 200px; /* 원하는 높이 */
}
}

View File

@@ -0,0 +1,127 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
header("Content-Type: application/json"); // Set content type for JSON response
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
$tablename = 'bendingfee';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
include $_SERVER['DOCUMENT_ROOT'] . "/bendingfee/_request.php"; // Ensure this file properly sets all needed variables
$searchtag = $basicdate . ' ' . $firstitem . ' ' . $seconditem . ' ' . $prodcode . ' ' . $proditem . ' ' . $material . ' ' . $itemcode . ' ' . $unit . ' ' . $su . ' ' . $unitprice . ' ' . $update_log . ' ' . $unitList . ' ' . $memo;
$searchtag = trim($searchtag); // 양쪽 공백 제거
if ($mode == "modify") {
$num = isset($_POST['num']) ? $_POST['num'] : 0;
$update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . "&#10" . (isset($_POST['update_log']) ? $_POST['update_log'] : '');
try {
$pdo->beginTransaction();
$sql = "UPDATE " . $DB . "." . $tablename . "
SET basicdate = ?, firstitem = ?, seconditem = ?, prodcode = ?, proditem = ?, material = ?,
itemcode = ?, unit = ?, su = ?, unitprice = ?, memo = ?, update_log = ?, searchtag = ?, unitList = ?
WHERE num = ?";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $basicdate, PDO::PARAM_STR);
$stmh->bindValue(2, $firstitem, PDO::PARAM_STR);
$stmh->bindValue(3, $seconditem, PDO::PARAM_STR);
$stmh->bindValue(4, $prodcode, PDO::PARAM_STR);
$stmh->bindValue(5, $proditem, PDO::PARAM_STR);
$stmh->bindValue(6, $material, PDO::PARAM_STR);
$stmh->bindValue(7, $itemcode, PDO::PARAM_STR);
$stmh->bindValue(8, $unit, PDO::PARAM_STR);
$stmh->bindValue(9, $su, PDO::PARAM_INT);
$stmh->bindValue(10, $unitprice, PDO::PARAM_STR);
$stmh->bindValue(11, $memo, PDO::PARAM_STR);
$stmh->bindValue(12, $update_log, PDO::PARAM_STR);
$stmh->bindValue(13, $searchtag, PDO::PARAM_STR);
$stmh->bindValue(14, $unitList, PDO::PARAM_STR);
$stmh->bindValue(15, $num, PDO::PARAM_INT);
$stmh->execute();
$pdo->commit();
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: " . $Exception->getMessage();
}
} elseif ($mode == "delete") {
$num = isset($_POST['num']) ? $_POST['num'] : 0;
$update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . "&#10" . (isset($_POST['update_log']) ? $_POST['update_log'] : '');
try {
$pdo->beginTransaction();
$sql = "UPDATE " . $DB . "." . $tablename . " SET update_log = ?, is_deleted = ? WHERE num = ? LIMIT 1";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $update_log, PDO::PARAM_STR);
$stmh->bindValue(2, 1, PDO::PARAM_INT); // 1 means deleted
$stmh->bindValue(3, $num, PDO::PARAM_INT);
$stmh->execute();
$pdo->commit();
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: " . $Exception->getMessage();
}
} else {
$update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . "&#10";
try {
$pdo->beginTransaction();
$sql = "INSERT INTO " . $DB . "." . $tablename . " (basicdate, firstitem, seconditem, prodcode, proditem,
material, itemcode, unit, su, unitprice, memo, update_log, searchtag, unitList)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmh = $pdo->prepare($sql);
$stmh->bindValue(1, $basicdate, PDO::PARAM_STR);
$stmh->bindValue(2, $firstitem, PDO::PARAM_STR);
$stmh->bindValue(3, $seconditem, PDO::PARAM_STR);
$stmh->bindValue(4, $prodcode, PDO::PARAM_STR);
$stmh->bindValue(5, $proditem, PDO::PARAM_STR);
$stmh->bindValue(6, $material, PDO::PARAM_STR);
$stmh->bindValue(7, $itemcode, PDO::PARAM_STR);
$stmh->bindValue(8, $unit, PDO::PARAM_STR);
$stmh->bindValue(9, $su, PDO::PARAM_INT);
$stmh->bindValue(10, $unitprice, PDO::PARAM_STR);
$stmh->bindValue(11, $memo, PDO::PARAM_STR);
$stmh->bindValue(12, $update_log, PDO::PARAM_STR);
$stmh->bindValue(13, $searchtag, PDO::PARAM_STR);
$stmh->bindValue(14, $unitList, PDO::PARAM_STR);
$stmh->execute();
$pdo->commit();
} catch (PDOException $Exception) {
$pdo->rollBack();
print "오류: " . $Exception->getMessage();
}
}
$data = [
'status' => 'success',
'mode' => $mode,
'basicdate' => $basicdate,
'firstitem' => $firstitem,
'seconditem' => $seconditem,
'prodcode' => $prodcode,
'proditem' => $proditem,
'material' => $material,
'itemcode' => $itemcode,
'unit' => $unit,
'su' => $su,
'unitprice' => $unitprice,
'memo' => $memo,
'unitList' => $unitList
];
echo json_encode($data, JSON_UNESCAPED_UNICODE);
?>

603
bendingfee_backup/list.php Normal file
View File

@@ -0,0 +1,603 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
// 첫 화면 표시 문구
$title_message = '절곡 BOM단가';
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> <?=$title_message?> </title>
<link href="css/style.css" rel="stylesheet" >
<style>
#bendTableToggle {
cursor: pointer;
}
</style>
</head>
<body>
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); ?>
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
$tablename = 'price_bend';
try {
// 최신 데이터를 가져오기 위해 ORDER BY와 LIMIT을 추가
$sql = "SELECT * FROM {$DB}.$tablename where 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'];
$bendingFeeDate = $row['registedate'];
} catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
$tablename = 'bendingfee';
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$fromdate = isset($_REQUEST['fromdate']) ? $_REQUEST['fromdate'] : '';
$todate = isset($_REQUEST['todate']) ? $_REQUEST['todate'] : '';
$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
// 현재 날짜
$currentDate = date("Y-m-d");
// fromdate 또는 todate가 빈 문자열이거나 null인 경우
if ($fromdate === "" || $fromdate === null || $todate === "" || $todate === null) {
$fromdate = date("Y-m-d", strtotime("2024-01-01"));
$todate = $currentDate; // 현재 날짜
$Transtodate = $todate;
} else {
// fromdate와 todate가 모두 설정된 경우 (기존 로직 유지)
$Transtodate = $todate;
}
$sql=" select * from " . $DB . "." . $tablename ;
$sum=array();
$now = date("Y-m-d"); // 현재 날짜와 크거나 같으면 출고예정으로 구분
$orderby="order by num desc ";
$attached='';
$whereattached = '';
$SettingDate=" basicdate ";
$common= $SettingDate . " between '$fromdate' and '$Transtodate' and is_deleted IS NULL ";
$andPhrase= " and " . $common . $orderby ;
$wherePhrase= " where " . $common . $orderby ;
$firstitem = isset($_POST['firstitem']) ? $_POST['firstitem'] : '';
$seconditem = isset($_POST['seconditem']) ? $_POST['seconditem'] : '';
$prodcode = isset($_POST['prodcode']) ? $_POST['prodcode'] : '';
// 필터링 조건 추가
$whereClause = [];
$search = str_replace(' ', '', $search); // 기존 검색어 처리
if ($firstitem !== '') {
$whereClause[] = "firstitem = '$firstitem' ";
}
if ($seconditem !== '') {
$whereClause[] = "seconditem = '$seconditem' ";
}
if ($prodcode !== '') {
$whereClause[] = "prodcode = '$prodcode' ";
}
if ($search !== '') {
$whereClause[] = "(replace(searchtag, ' ', '') LIKE '%$search%')";
}
// where 조건을 조합
$whereQuery = implode(' AND ', $whereClause);
// 최종 SQL 쿼리
$sql = "SELECT * FROM " . $DB . "." . $tablename . " WHERE " . $common;
if (!empty($whereQuery)) {
$sql .= " AND " . $whereQuery;
}
$sql .= $orderby;
try {
$stmh = $pdo->query($sql);
$rows = $stmh->fetchAll(PDO::FETCH_ASSOC); // 모든 데이터를 한 번에 가져오기
$total_row = count($rows); // 가져온 데이터의 행 수 계산
// var_dump($total_row);
$start_num = $total_row;
} catch (PDOException $Exception) {
echo "오류: " . $Exception->getMessage();
}
// print $sql;
?>
<form id="board_form" name="board_form" method="post" action="list.php?mode=search">
<div class="container">
<div class="card mb-2 mt-2">
<div class="card-body">
<div class="d-flex p-1 m-1 mt-1 justify-content-center align-items-center">
<h5><?=$title_message?></h5>
<button type="button" class="btn btn-dark btn-sm mx-2" onclick='location.reload();' > <i class="bi bi-arrow-clockwise"></i> </button>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'] . '/lot/lotTable.php'; ?>
<div class="d-flex justify-content-center align-items-center mb-4">
<button type="button" class="btn btn-dark btn-sm mx-1" onclick="gotoBendingListBtn(); return false; " > <i class="bi bi-journal-text"></i> 절곡 기초자료 이동 </button>
<button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadmodelBtn(); return false; " > <i class="bi bi-pencil-square"></i> 셔터 모델관리 </button>
<button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadQCBtn(); return false; " > <i class="bi bi-pencil-square"></i> 절곡물 품목관리 </button>
<button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadTreeBtn(); return false; " > <i class="bi bi-pencil-square"></i> 모델 Tree </button>
<button type="button" class="btn btn-primary btn-sm mx-1" onclick="previousBtn(); return false; " > 새로운 BOM 화면 </button>
</div>
<div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-center align-items-center">
<!-- 기존 검색어 입력 -->
<ion-icon name="caret-forward-outline"></ion-icon> <?= $total_row ?> &nbsp;
<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" style="width:100px;" value="<?=$todate?>" > &nbsp;
<!-- 대분류 -->
<select id="firstitem" name="firstitem" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
<option value="">(대분류)</option>
<option value="스크린" <?= ($firstitem == '스크린') ? 'selected' : '' ?>>스크린</option>
<option value="철재" <?= ($firstitem == '철재') ? 'selected' : '' ?>>철재</option>
</select> &nbsp;
<!-- 중분류 -->
<?php
// 예: getCategoryByName($parentName) 함수가 존재하며,
// '절곡물'이라는 2단계 카테고리의 자식(3단계) 카테고리 이름 배열을 리턴한다.
$l3_list = getCategoryByName('스크린','절곡물');
?>
<select id="seconditem" name="seconditem" class="form-select mx-1 d-block w-auto" 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>
<!-- 제품모델(KSS01 등) 선택 -->
<?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 d-block w-auto" 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>
<div class="inputWrap">
<input type="text" id="search" class="form-control" style="width:150px;" name="search" autocomplete="off" value="<?=$search?>" onKeyPress="if (event.keyCode==13){ enter(); }">
<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>
&nbsp;&nbsp;&nbsp;
<button type="button" class="btn btn-dark btn-sm me-1" id="writeBtn"><i class="bi bi-pencil-fill"></i> 신규</button>
</div>
</div> <!--card-body-->
</div> <!--card -->
</div> <!--container-fluid -->
<div class="container-fluid">
<div class="row justify-content-center">
<div class="card w-50">
<div class="card-body">
<div class="d-flex justify-content-center align-items-center" >
<h5 class="card-title text-center">절곡 ㎡ 단가표 (기준일: <?=$bendingFeeDate?>) </h5>
<span id="bendTableUnitToggle" class="badge bg-secondary ms-3 me-2">
<i class="bi bi-chevron-down"></i>
</span>
</div>
<table id="item_bendTable" class="table table-bordered table-hover">
<thead class="table-primary text-center">
<tr>
<th class="align-middle">품목</th>
<th class="align-middle">규격</th>
<th class="align-middle">두께(T)</th>
<th class="align-middle">비중</th>
<th class="align-middle">㎡ / 단가</th>
</tr>
</thead>
<tbody>
<!-- Additional Rows Go Here -->
</tbody>
</table>
</div>
</div>
</div> <!--row-->
<div class="d-flex justify-content-center align-items-center">
<table class="table table-hover" id="myTable">
<thead class="table-primary">
<tr>
<!-- 두번째 th에 체크박스 추가 (data-num="all") -->
<th class="text-center" style="width:30px;">
<input type="checkbox" id="selectAll" data-num="all" />
</th>
<th class="text-center" style="width:50px;">번호</th>
<th class="text-center" style="width:100px;">기준일</th>
<th class="text-center" style="width:150px;">대분류</th>
<th class="text-center" style="width:150px;">중분류</th>
<th class="text-center" style="width:150px;">제품코드</th>
<th class="text-center" style="width:150px;"> 품목/규격 </th>
<th class="text-center" style="width:150px;">마감 재질</th>
<th class="text-center" style="width:100px;">단위</th>
<th class="text-center" style="width:100px;">수량</th>
<th class="text-center" style="width:150px;">산출단가/M</th>
<th class="text-center" style="width:400px;">메모</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmh = $pdo->query($sql);
$rows = $stmh->fetchAll(PDO::FETCH_ASSOC); // 모든 데이터를 한 번에 가져오기
$total_row = count($rows); // 가져온 데이터의 행 수 계산
$start_num = $total_row;
foreach ($rows as $row) {
?>
<tr onclick="redirectToView('<?= $row['num'] ?>', '<?= $tablename ?>')">
<!-- 각 행에 체크박스 추가하고 data-num에 row의 num 값 지정 -->
<td class="text-center">
<input type="checkbox" class="rowCheckbox" data-num="<?= $row['num'] ?>" onclick="event.stopPropagation();">
</td>
<td class="text-center"><?= $start_num ?></td>
<td class="text-center"><?= $row['basicdate'] ?></td>
<td class="text-center"><?= $row['firstitem'] ?></td>
<td class="text-center"><?= $row['seconditem'] ?></td>
<td class="text-center"><?= $row['prodcode'] ?></td>
<td class="text-center"><?= $row['proditem'] ?></td>
<td class="text-center"><?= $row['material'] ?></td>
<td class="text-center"><?= $row['unit'] ?></td>
<td class="text-center"><?= $row['su'] ?></td>
<td class="text-center"><?= $row['unitprice'] ?></td>
<td class="text-start"><?= $row['memo'] ?></td>
</tr>
<?php
$start_num--;
}
} catch (PDOException $Exception) {
echo "오류: " . $Exception->getMessage();
}
?>
</tbody>
</table>
</div>
</div> <!--container-->
</form>
<div class="container-fluid mt-3 mb-3">
<? include '../footer.php'; ?>
</div>
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
});
var dataTable; // DataTables 인스턴스 전역 변수
var feepageNumber; // 현재 페이지 번호 저장을 위한 전역 변수
$(document).ready(function() {
// DataTables 초기 설정
dataTable = $('#myTable').DataTable({
"paging": true,
"ordering": true,
"searching": true,
"pageLength": 100,
"lengthMenu": [100, 200, 500, 1000],
"language": {
"lengthMenu": "Show _MENU_ entries",
"search": "Live Search:"
},
"order": [[0, 'desc']]
});
// 페이지 번호 복원 (초기 로드 시)
var savedPageNumber = getCookie('feepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
// 페이지 변경 이벤트 리스너
dataTable.on('page.dt', function() {
var feepageNumber = dataTable.page.info().page + 1;
setCookie('feepageNumber', feepageNumber, 10); // 쿠키에 페이지 번호 저장
});
// 페이지 길이 셀렉트 박스 변경 이벤트 처리
$('#myTable_length select').on('change', function() {
var selectedValue = $(this).val();
dataTable.page.len(selectedValue).draw(); // 페이지 길이 변경 (DataTable 파괴 및 재초기화 없이)
// 변경 후 현재 페이지 번호 복원
savedPageNumber = getCookie('feepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
});
});
function restorePageNumber() {
var savedPageNumber = getCookie('feepageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw('page');
}
location.reload(true);
}
function redirectToView(num, tablename) {
var url = "write_form.php?mode=view&num=" + num + "&tablename=" + tablename;
customPopup(url, '수주내역', 1800, 900);
}
$(document).ready(function(){
$("#writeBtn").click(function(){
var tablename = '<?php echo $tablename; ?>';
var url = "write_form.php?tablename=" + tablename;
customPopup(url, '수주내역', 1800, 900);
});
});
function SearchEnter(event){
if(event.keyCode == 13){
saveSearch();
}
}
function saveSearch() {
let searchInput = document.getElementById('search');
let searchValue = searchInput.value;
if (searchValue === "") {
document.getElementById('board_form').submit();
}
}
$(document).ready(function(){
$("#denkriModel").hover(function(){
$("#customTooltip").show();
}, function(){
$("#customTooltip").hide();
});
$("#searchBtn").click(function(){
saveSearch();
});
});
function initializePage() {
// 절곡 단가
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 = [];
}
}
// item_bend가 올바른 배열인지 확인
if (!Array.isArray(item_bend)) {
item_bend = [];
}
console.log(item_bend);
var tableBody = $('#item_bendTable tbody'); // 테이블의 tbody 선택
// JSON 데이터를 순회하며 각 행을 추가하고, 값을 채워 넣음
item_bend.forEach(function(rowData) {
addRow_bend(tableBody, rowData);
});
}
function inputNumberFormat(obj) {
obj.value = obj.value.replace(/[^0-9]/g, '');
}
// 숫자에 3자리마다 콤마를 추가하는 함수
function numberWithCommas(x) {
if (!x) return '';
x = x.toString().replace(/[^0-9.-]/g, ''); // 숫자와 '-' 기호만 남김
return x.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function addRow_bend(tableBody, rowData) {
var newRow = $('<tr>');
// col1부터 col18까지 채우기
for (let i = 1; i <= 18; i++) {
let colValue = rowData['col' + i] || ''; // 값이 없으면 빈 문자열 사용
// 특정 열만 readonly 속성 부여
if ([1, 2, 5, 6, 17].includes(i)) {
newRow.append('<td><input type="text" name="col' + i + '[]" value="' + colValue + '" class="form-control text-center number-format col' + i + '" autocomplete="off" readonly></td>');
}
}
// 새 행을 테이블에 추가
tableBody.append(newRow);
}
$(document).ready(function() {
initializePage();
// Toggle button for bendTable
$("#bendTableUnitToggle").on("click", function() {
var showBendTable = getCookie("showBendTable");
var bendTable = $("#item_bendTable");
if (showBendTable === "show") {
bendTable.css("display", "none");
setCookie("showBendTable", "hide", 10);
} else {
bendTable.css("display", "block");
setCookie("showBendTable", "show", 10);
}
});
// Check the cookie value on page load and set the table visibility
var showBendTable = getCookie("showBendTable");
var bendTable = $("#item_bendTable");
if (showBendTable === "show") {
bendTable.css("display", "block");
} else {
bendTable.css("display", "none");
}
});
// Enterkey 동작
function enter()
{
$("#board_form").submit();
}
// 절곡기초 바라시 이동
function gotoBendingListBtn() {
var title = '<?=$title_message;?>';
var url = '../bending/list.php?header=header';
location.href = url;
}
// 모델관리
function loadmodelBtn() {
var title = '<?=$title_message;?>';
popupCenter('../models/modelslist.php', title, 1100, 900);
}
// 품목관리
function loadQCBtn() {
var title = '<?=$title_message;?>';
popupCenter('../models/itemlist.php', title, 1100, 900);
}
// 모델트리 호출
function loadTreeBtn() {
var title = '<?=$title_message;?>';
popupCenter('../modelsTree/modelsTree.php', title, 1100, 900);
}
// 새로운 화면 호출
function previousBtn() {
var url = '../bendingfee/list.php?header=header';
location.href = url;
}
$(document).ready(function(){
// 방문기록 남김
var title_message = '<?php echo $title_message ; ?>';
saveMenuLog(title_message);
});
</script>
<!-- ★ 체크박스 관련 기능 추가 스크립트 ★ -->
<script>
$(document).ready(function(){
// 헤더의 "select all" 체크박스 클릭 시 모든 행의 체크박스 상태를 변경
$('#selectAll').click(function(){
var checked = $(this).prop('checked');
$('.rowCheckbox').prop('checked', checked);
});
// "전체 복사" 버튼 클릭 시 선택된 체크박스의 data-num 값을 복사
$('#copyBtn').click(function(){
var selectedData = [];
$('.rowCheckbox:checked').each(function(){
selectedData.push($(this).data('num'));
});
if(selectedData.length > 0){
var copyText = selectedData.join(', ');
copyToClipboard(copyText);
alert('선택된 데이터가 복사되었습니다: ' + copyText);
} else {
alert('선택된 데이터가 없습니다.');
}
});
});
// 텍스트를 클립보드로 복사하는 함수
function copyToClipboard(text) {
var tempInput = $("<input>");
$("body").append(tempInput);
tempInput.val(text).select();
document.execCommand("copy");
tempInput.remove();
}
//Lot No 부여법 (펼치고 접기)
$(document).ready(function() {
$("#bendTableToggle").on("click", function() {
var showLotList_models = getCookie("showLotList_models");
var bendTable = $("#item_Table");
if (showLotList_models === "show") {
bendTable.css("display", "none");
setCookie("showLotList_models", "hide", 10);
} else {
bendTable.css("display", "block");
setCookie("showLotList_models", "show", 10);
}
});
// Check the cookie value on page load and set the table visibility
var showLotList_models = getCookie("showLotList_models");
var bendTable = $("#item_Table");
if (showLotList_models === "show") {
bendTable.css("display", "block");
} else {
bendTable.css("display", "none");
}
});
</script>
</body>
</html>

View File

@@ -0,0 +1,69 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
// searchBending.php
require_once($_SERVER['DOCUMENT_ROOT'].'/lib/mydb.php');
$pdo = db_connect();
$item_sep = $_GET['item_sep'] ?? ''; // 대분류
$item_bending = $_GET['item_bending'] ?? '';
$sql = "SELECT * FROM {$DB}.bending WHERE is_deleted IS NULL";
$params = [];
if($item_sep !== ''){
$sql .= " AND item_sep = :item_sep";
$params[':item_sep'] = $item_sep;
}
if($item_bending !== ''){
$sql .= " AND item_bending = :item_bending";
$params[':item_bending'] = $item_bending;
}
$sql .= " ORDER BY num DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<table class="table table-bordered">
<thead class="table-secondary" >
<tr>
<th>대분류</th>
<th>중분류</th>
<th>품명</th>
<th>규격(가로*세로)</th>
<th>재질</th>
<th>전체 폭</th>
<th>이미지</th>
</tr>
</thead>
<tbody>
<?php foreach($results as $row): ?>
<tr onclick='selectBendingItem(<?php echo json_encode($row, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT); ?>)'>
<td><?php echo htmlspecialchars($row['item_sep']); ?></td>
<td><?php echo htmlspecialchars($row['item_bending']); ?></td>
<td><?php echo htmlspecialchars($row['itemName']); ?></td>
<td><?php echo htmlspecialchars($row['item_spec']); ?></td>
<td><?php echo htmlspecialchars($row['material']); ?></td>
<td><?php
$sumList = json_decode($row['sumList'], true);
echo htmlspecialchars(end($sumList));
?></td>
<td class="text-center">
<?php
$img = htmlspecialchars($row['imgdata'], ENT_QUOTES, 'UTF-8');
if ($img) {
$img_path = "../bending/img/" . $img;
echo '<img src="' . $img_path . '" alt="이미지" style="max-width:100px;max-height:50px;">';
} else {
echo '(선택)';
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

52
bendingfee_backup/sql.php Normal file
View File

@@ -0,0 +1,52 @@
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
print $DB;
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php"); // DB 연결 파일
$pdo = db_connect(); // PDO 연결
try {
// 1. BDmodels 테이블 생성
$sql_models = "
CREATE TABLE IF NOT EXISTS {$DB}.BDmodels (
model_id INT AUTO_INCREMENT PRIMARY KEY,
model_name VARCHAR(255) NOT NULL, -- KSS01 등 모델
finishing_type ENUM('SUS', 'EGI') NOT NULL DEFAULT 'SUS',
seconditem TEXT, -- 중분류
unitprice TEXT, -- 산출단가합
description TEXT, -- 메모
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;
";
// 2. BDparts 테이블 생성
$sql_parts = "
CREATE TABLE IF NOT EXISTS {$DB}.BDparts (
part_id INT AUTO_INCREMENT PRIMARY KEY,
model_id INT NOT NULL,
part_name VARCHAR(255) NOT NULL,
spec VARCHAR(255),
unit VARCHAR(50),
quantity DECIMAL(10,0) DEFAULT 1,
price_factor DECIMAL(10,0) DEFAULT 1, -- 동적 가격 계산 보정값
price DECIMAL(10,0) DEFAULT 1, -- 단가
is_deleted TINYINT(1) DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (model_id) REFERENCES BDmodels(model_id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
";
// SQL 실행
// $pdo->exec($sql_models);
$pdo->exec($sql_parts);
echo "✅ BDmodels, BDparts 테이블이 성공적으로 생성되었습니다.";
} catch (PDOException $e) {
echo "❌ 오류 발생: " . $e->getMessage();
}
?>

View File

@@ -0,0 +1,764 @@
<?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>