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

1688 lines
70 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;
}
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"] : "";
if($mode === 'copy')
$title_message = "(데이터복사) 공사 수주";
else
$title_message = "공사 수주 " ;
?>
<title> <?=$title_message?> </title>
<style>
input {
autocomplete: off;
}
textarea {
overflow: hidden;
resize: none; /* 사용자 크기 조절을 방지 */
}
.custom-file-upload {
display: inline-block;
cursor: pointer;
color: #007bff;
font-size: 1.2rem;
}
.custom-file-upload input[type="file"] {
display: none;
}
.custom-file-upload {
display: inline-block;
cursor: pointer;
color: #007bff;
font-size: 1.2rem;
}
.custom-file-upload input[type="file"] {
display: none;
}
</style>
</head>
<?
include $_SERVER['DOCUMENT_ROOT'] . '/mymodal.php';
// 첨부 이미지에 대한 부분
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
$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";
$item_file_0 = $row["file_name_0"];
$item_file_1 = $row["file_name_1"];
$item_file_2 = $row["file_name_2"];
$copied_file_0 = "../uploads/". $row["file_copied_0"];
$copied_file_1 = "../uploads/". $row["file_copied_1"];
$copied_file_2 = "../uploads/". $row["file_copied_2"];
function formatDate($date) {
return ($date != "0000-00-00" && !empty($date)) ? date("Y-m-d", strtotime($date)) : "";
}
$workday = formatDate($row["workday"]);
$cableday = formatDate($row["cableday"]);
$asday = formatDate($row["asday"]);
$condate = formatDate($row["condate"]);
$condate1 = formatDate($row["condate1"]);
$condate2 = formatDate($row["condate2"]);
$billdate1 = formatDate($row["billdate1"]);
$billdate2 = formatDate($row["billdate2"]);
$billdate3 = formatDate($row["billdate3"]);
$billdate4 = formatDate($row["billdate4"]);
$billdate5 = formatDate($row["billdate5"]);
$billdate6 = formatDate($row["billdate6"]);
$endworkday = formatDate($row["endworkday"]);
$endcableday = formatDate($row["endcableday"]);
$depositdate1 = formatDate($row["depositdate1"]);
$depositdate2 = formatDate($row["depositdate2"]);
$depositdate3 = formatDate($row["depositdate3"]);
$depositdate4 = formatDate($row["depositdate4"]);
$depositdate5 = formatDate($row["depositdate5"]);
$depositdate6 = formatDate($row["depositdate6"]);
$asproday = formatDate($row["asproday"]);
$asendday = formatDate($row["asendday"]);
$claimdate1 = formatDate($row["claimdate1"]);
$claimdate2 = formatDate($row["claimdate2"]);
$claimdate3 = formatDate($row["claimdate3"]);
$claimdate4 = formatDate($row["claimdate4"]);
$claimdate5 = formatDate($row["claimdate5"]);
$claimdate6 = formatDate($row["claimdate6"]);
$promiseday = formatDate($row["promiseday"]);
$setdate = formatDate($row["setdate"]);
// 3자리마다 콤마를 추가하는 함수
function formatNumberWithCommas($number) {
if (is_numeric($number)) {
return number_format($number);
}
return $number;
}
// 변수를 선언하고 3자리마다 콤마를 추가
$estimate1_supply = isset($row['estimate1_supply']) ? formatNumberWithCommas($row['estimate1_supply']) : '';
$estimate1_vat = isset($row['estimate1_vat']) ? formatNumberWithCommas($row['estimate1_vat']) : '';
$estimate2_supply = isset($row['estimate2_supply']) ? formatNumberWithCommas($row['estimate2_supply']) : '';
$estimate2_vat = isset($row['estimate2_vat']) ? formatNumberWithCommas($row['estimate2_vat']) : '';
$estimate3_supply = isset($row['estimate3_supply']) ? formatNumberWithCommas($row['estimate3_supply']) : '';
$estimate3_vat = isset($row['estimate3_vat']) ? formatNumberWithCommas($row['estimate3_vat']) : '';
$estimate4_supply = isset($row['estimate4_supply']) ? formatNumberWithCommas($row['estimate4_supply']) : '';
$estimate4_vat = isset($row['estimate4_vat']) ? formatNumberWithCommas($row['estimate4_vat']) : '';
$bill1_supply = isset($row['bill1_supply']) ? formatNumberWithCommas($row['bill1_supply']) : '';
$bill1_vat = isset($row['bill1_vat']) ? formatNumberWithCommas($row['bill1_vat']) : '';
$bill2_supply = isset($row['bill2_supply']) ? formatNumberWithCommas($row['bill2_supply']) : '';
$bill2_vat = isset($row['bill2_vat']) ? formatNumberWithCommas($row['bill2_vat']) : '';
$bill3_supply = isset($row['bill3_supply']) ? formatNumberWithCommas($row['bill3_supply']) : '';
$bill3_vat = isset($row['bill3_vat']) ? formatNumberWithCommas($row['bill3_vat']) : '';
$bill4_supply = isset($row['bill4_supply']) ? formatNumberWithCommas($row['bill4_supply']) : '';
$bill4_vat = isset($row['bill4_vat']) ? formatNumberWithCommas($row['bill4_vat']) : '';
$bill5_supply = isset($row['bill5_supply']) ? formatNumberWithCommas($row['bill5_supply']) : '';
$bill5_vat = isset($row['bill5_vat']) ? formatNumberWithCommas($row['bill5_vat']) : '';
$bill6_supply = isset($row['bill6_supply']) ? formatNumberWithCommas($row['bill6_supply']) : '';
$bill6_vat = isset($row['bill6_vat']) ? formatNumberWithCommas($row['bill6_vat']) : '';
}
}catch (PDOException $Exception) {
print "오류: ".$Exception->getMessage();
}
}
if ($mode !== "modify" and $mode !== "copy" and $mode !== "view" ) {
include '_request.php';
}
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;
}
?>
<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 : '' ?>">
<input type="hidden" id="tablename" name="tablename" value="<?= isset($tablename) ? $tablename : '' ?>">
<input type="hidden" id="price" name="price" value="<?= isset($price) ? $price : '' ?>">
<input type="hidden" id="originalcost" name="originalcost" value="<?= isset($originalcost) ? $originalcost : '' ?>">
<input type="hidden" id="item" name="item" value="<?= isset($item) ? $item : '' ?>">
<input type="hidden" id="sum_bill" name="sum_bill" value="<?= isset($sum_bill) ? $sum_bill : 0 ?>">
<input type="hidden" id="sum_deposit" name="sum_deposit" value="<?= isset($sum_deposit) ? $sum_deposit : 0 ?>">
<input type="hidden" id="sum_receivable" name="sum_receivable" value="<?= isset($sum_receivable) ? $sum_receivable : 0 ?>">
<input type="hidden" id="accountList" name="accountList" >
<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-10" >
<div class="d-flex p-1 mb-1 justify-content-center align-items-center ">
<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">
<? if((int)$num>0) print ' <i class="bi bi-hdd-fill"></i> 저장'; else print ' <i class="bi bi-hdd-fill"></i> 저장'; ?></button>
<? } ?>
<?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>
<? } ?>
<button type="button" class="btn btn-outline-dark btn-sm me-2" id="showlogBtn" > H
</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 class="row " >
<?php if ($chkMobile): ?>
<div class="col-sm-12 rounded" >
<?php else: ?>
<div class="col-lg-6 col-sm-6 rounded" >
<?php endif; ?>
<div class="card">
<div class="card-body text-center">
<div class="d-flex p-1 mb-1 justify-content-start align-items-center">
<span class="text-center badge bg-secondary fs-6 me-3"> 견적 </span>
<button type='button' class='btn btn-primary btn-sm viewNoBtn add-row-estimate me-2' data-table='estimateListTable' style='margin-right: 5px;'>+</button>
</div>
<div class="row p-1 mb-1 justify-content-center align-items-center">
<table id="estimateListTable" class="table table-hover table-bordered">
<thead>
<tr>
<th class="text-center" style="width:8%;">차수</th>
<th class="text-center" style="width:8%;">견적일</th>
<th class="text-center" style="width:15%;">공급가액</th>
<th class="text-center" style="width:12%;">부가세</th>
<th class="text-center" style="width:15%;">합계</th>
<th class="text-center" style="width:40%;"><i class="bi bi-paperclip"></i> 첨부</th>
</tr>
</thead>
<tbody id="estimateListBody">
<!-- JavaScript에서 동적으로 생성된 행이 여기에 추가됩니다 -->
</tbody>
</table>
</div>
</div>
</div>
<div class="card">
<div class="card-body text-center">
<div class="d-flex p-1 mb-1 justify-content-start align-items-center">
<span class="text-center badge bg-success fs-6 me-3">계산서/입금</span>
<button type='button' class='btn btn-primary btn-sm viewNoBtn add-row me-2' data-table='accountListTable' style='margin-right: 5px;'>+</button>
</div>
<div class="row p-1 mb-1 justify-content-center align-items-center">
<table id="accountListTable" class="table table-hover table-bordered">
<thead>
<tr>
<th class="text-center" style="width:10%;">차수</th>
<th class="text-center" style="width:15%;">세금계산서발행</th>
<th class="text-center" style="width:15%;">공급가액</th>
<th class="text-center" style="width:15%;">부가세</th>
<th class="text-center" style="width:15%;">발행합계</th>
<th class="text-center" style="width:15%;">입금일자</th>
<th class="text-center" style="width:15%;">입금액</th>
</tr>
</thead>
<tbody id="accountListBody">
<!-- JavaScript에서 동적으로 생성된 행이 여기에 추가됩니다 -->
</tbody>
<tfoot>
<!-- 합계 행 추가 -->
<tr>
<td class="text-center fw-bold">합계</td>
<td></td> <!-- 빈 셀 -->
<td><input type="text" id="total_supply" name="total_supply" class="form-control text-end" placeholder="공급가액 합계" readonly /></td>
<td><input type="text" id="total_vat" name="total_vat" class="form-control text-end" placeholder="부가세 합계" readonly /></td>
<td><input type="text" id="total_bill" name="total_bill" class="form-control text-end" placeholder="발행금액 합계" readonly /></td>
<td></td>
<td><input type="text" id="total_deposit" name="total_deposit" class="form-control text-end" placeholder="입금액 합계" readonly /></td>
</tr>
</tfoot>
</table>
</div>
<div class="d-flex p-1 mb-1 justify-content-center align-items-center">
<div class="row">
<div class="col-lg-6 col-sm-6 ">
<table class="table table-hover table-bordered" style="border: 2px solid blue;">
<thead>
<tr>
<th class="text-center"> 발행 미수금 </th>
<th class="text-center"> 총 미수금 </th>
<th class="text-center">입금약속일</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display:none;" >
<input type="text" id="decided_estimate" name="decided_estimate" class="form-control text-end" value="<?=$decided_estimate?>" readonly />
</td>
<td style="display:none;" >
<input type="text" id="issued_amount" name="issued_amount" class="form-control text-end" value="<?=$issued_amount?>" readonly />
</td>
<td class="text-danger fw-bold text-end">
<input type="text" id="issued_receivable" name="issued_receivable" class="form-control text-end text-primary fw-bold" value="<?=$issued_receivable?>" readonly />
</td>
<td class="text-danger fw-bold text-end">
<input type="text" id="total_receivable" name="total_receivable" class="form-control text-end text-danger fw-bold" value="<?=$total_receivable?>" readonly />
</td>
<td>
<input type="date" id="promiseday" name="promiseday" value="<?=$promiseday?>" class="form-control" placeholder="입금약속일" />
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-6 col-sm-6 ">
<div class="d-flex p-1 mb-1 justify-content-center align-items-center">
<table class="table table-hover table-bordered " style="border: 2px solid orange;">
<thead>
<tr>
<th colspan="3" class="text-center">하자보증기간</th>
</tr>
<tr>
<th class="text-center">시작일</th>
<th class="text-center">종료일</th>
<th class="text-center w100px">기간</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="date" id="warrantyFromDate" name="warrantyFromDate" value="<?=$warrantyFromDate?>" class="form-control text-end" onchange="calculateWarrantyPeriod()" />
</td>
<td>
<input type="date" id="warrantyToDate" name="warrantyToDate" value="<?=$warrantyToDate?>" class="form-control text-end" onchange="calculateWarrantyPeriod()" />
</td>
<td>
<input type="text" id="warrantyPeriod" name="warrantyPeriod" value="<?=$warrantyPeriod?>" class="form-control text-end" readonly />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="d-flex p-1 mb-1 justify-content-center align-items-center">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class="text-center" >경리부 수금관련 기록</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3"><textarea rows="5" cols="32" id="accountnote" name="accountnote" class="form-control" placeholder="경리부 기록/메모/노트"><?=$accountnote?></textarea></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php if ($chkMobile): ?>
<div class="col-sm-12 rounded" >
<?php else: ?>
<div class="col-lg-6 col-sm-6 rounded" >
<?php endif; ?>
<div class="card align-middle">
<div class="card-body text-center">
<div class="d-flex p-1 mb-1 justify-content-start align-items-center ">
<span class="text-center badge bg-primary fs-6 me-5" > 공사진행현황 </span>
<input type="checkbox" name="checkbox" value="1" <?= $checkbox == "1" ? "checked" : "" ?>> 계약전
</div>
<div class="d-flex p-1 mb-1 justify-content-start align-items-center ">
<span class="text-center text-success fs-6 me-5" >
요청사항 선택 :
<?php
$checkstep_options = ["없음", "상담요청", "방문요청", "실측요청", "발주요청", "결선요청", "견적요청"];
foreach ($checkstep_options as $option) {
echo $option . ' <input type="radio" name="checkstep" value="' . $option . '" ' . ($checkstep == $option ? 'checked' : '') . '> ';
}
?>
</span>
</div>
<div class="d-flex p-1 mb-1 justify-content-start align-items-center ">
<table class="table table-bordered">
<tbody>
<tr>
<td class="text-end" style="width:10%;">현장명 </td>
<td colspan="3" style="width:30%;"><input type="text" name="workplacename" value="<?= $workplacename ?>" class="form-control text-start" placeholder="현장명" required></td>
<td class="text-end" style="width:10%;">공사담당 </td>
<td style="width:20%;"><input type="text" name="chargedperson" value="<?= $chargedperson ?>" class="form-control" placeholder="공사담당"></td>
</tr>
<tr>
<td class="text-end" style="width:10%;">현장주소 </td>
<td colspan="3" ><input type="text" name="address" value="<?= $address ?>" class="form-control text-start" placeholder="현장주소"></td>
<td class="text-end" style="width:10%;">등록일 </td>
<td style="width:20%;"><input type="date" id="regist_day" name="regist_day" value="<?= $regist_day ?>" class="form-control" ></td>
</tr>
<tr>
<td class="text-end">건설사 </td>
<td><input type="text" name="firstord" value="<?= $firstord ?>" class="form-control" placeholder="건설사"></td>
<td class="text-end" >담당 </td>
<td style="width:16%;"><input type="text" name="firstordman" value="<?= $firstordman ?>" class="form-control" placeholder="원청담당"></td>
<td class="text-end">연락처 </td>
<td><input type="text" name="firstordmantel" value="<?= $firstordmantel ?>" class="form-control" placeholder="연락번호"></td>
</tr>
<tr>
<td class="text-end">발주처 </td>
<td><input type="text" name="secondord" value="<?= $secondord ?>" class="form-control" placeholder="발주처"></td>
<td class="text-end">담당 </td>
<td><input type="text" name="secondordman" value="<?= $secondordman ?>" class="form-control" placeholder="발주처 담당자"></td>
<td class="text-end">연락처 </td>
<td><input type="text" name="secondordmantel" value="<?= $secondordmantel ?>" class="form-control" placeholder="연락번호"></td>
</tr>
<tr>
<td colspan="3" class="text-end" style="width:35%;">발주처 결재 공무담당 </td>
<td><input type="text" id="claimperson" name="claimperson" value="<?= $claimperson ?>" class="form-control" placeholder="공무담당"></td>
<td class="text-end">연락처 </td>
<td><input type="text" name="claimtel" value="<?= $claimtel ?>" class="form-control" placeholder="공무전화"></td>
</tr>
<tr>
<td class="text-end">시공투입일 </td>
<td><input type="date" name="workday" value="<?= $workday ?>" class="form-control" placeholder="투입일" ></td>
<td class="text-end">시공팀 </td>
<td><input type="text" name="worker" value="<?= $worker ?>" class="form-control" placeholder="시공팀"></td>
<td class="text-end">시공완료일 </td>
<td><input type="date" name="endworkday" value="<?= $endworkday ?>" class="form-control" placeholder="시공완료일" ></td>
</tr>
<tr>
<td class="text-end">결선작업일 </td>
<td><input type="date" name="cableday" value="<?= $cableday ?>" class="form-control" placeholder="투입일" ></td>
<td class="text-end">결선팀 </td>
<td><input type="text" name="cablestaff" value="<?= $cablestaff ?>" class="form-control" placeholder="결선팀"></td>
<td class="text-end">결선완료일 </td>
<td><input type="date" name="endcableday" value="<?= $endcableday ?>" class="form-control" placeholder="결선완료일" ></td>
</tr>
<tr>
<td class="text-end">모터회사/용량 </td>
<td><input type="text" name="motormaker" value="<?= $motormaker ?>" class="form-control" placeholder="경동/인성/KST 등"></td>
<td class="text-end">전원사양 </td>
<td><input type="text" name="power" value="<?= $power ?>" class="form-control" placeholder="220v,380v"></td>
<td colspan="2" class="text-end"></td>
</tr>
<tr>
<td class="text-end">시공내역 및 수량 </td>
<td colspan="5"><textarea rows="3" id="worklist" name="worklist" class="form-control fw-bold" placeholder="셔터종류,수량 등 구체적 기술"><?= $worklist ?></textarea></td>
</tr>
<tr style="color:red;">
<td colspan="1" class="text-center text-danger fw-bold"> 설계변경 내역 </td>
<td colspan="5" class="text-center">
<textarea rows="3" id="change_worklist" name="change_worklist" class="form-control fw-bold" placeholder="설계변경 내역 기록" ><?=$change_worklist?></textarea>
</td>
<?php if((int)$num>0) { ?>
</tr>
<tr>
<td colspan="6" class="text-start text-secondary">
<span class="text-center badge bg-secondary fs-6 me-5 mb-2" > 경동기업 출고List </span>
<?php
try {
$sqloutput = "select * from $DB.output where con_num =" . $num;
$stmh = $pdo->query($sqloutput);
$temp = $stmh->rowCount();
?>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">공사번호</th>
<th class="text-center">출고일자</th>
<th class="text-center">접수일</th>
<th class="text-center">내역/코멘트</th>
</tr>
</thead>
<tbody>
<?php
while ($rowtmp = $stmh->fetch(PDO::FETCH_ASSOC)) {
$item_num = $rowtmp["num"];
$con_num = $rowtmp["con_num"];
$outdate = $rowtmp["outdate"];
$item_indate = $rowtmp["indate"];
$item_comment = $rowtmp["comment"];
if ($outdate != "") {
$week = array("(일)", "(월)", "(화)", "(수)", "(목)", "(금)", "(토)");
$outdate = $outdate . $week[date('w', strtotime($outdate))];
}
?>
<tr>
<td class="text-center"><a href="outputview.php?num=<?= $item_num ?>" target="_blank"><b><?= $con_num ?></b></a></td>
<td class="text-center" style="color: <?= $font ?>;"><b><?= substr($outdate, 0, 15) ?></b></td>
<td class="text-center"><b><?= substr($item_indate, 0, 10) ?></b></td>
<td class="text-center"><b><?= substr($item_comment, 0, 100) ?></b></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php
} catch (PDOException $Exception) {
print "오류: " . $Exception->getMessage();
}
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="d-flex p-1 mb-1 justify-content-start align-items-center ">
<table class="table table-bordered">
<tbody>
<tr>
<td class="text-end" style="width:15%;" >공사메모 </td>
<td colspan="8" >
<textarea rows="3" id="comment" name="comment" class="form-control" placeholder="공사관련 메모를 남겨주세요."><?=$comment?></textarea>
</td>
</tr>
<tr>
<td class="text-end" >자재출고 내역 정리</td>
<td colspan="8" >
<textarea rows="3" id="outputmemo" name="outputmemo" class="form-control" placeholder="자재 출고내역"><?=$outputmemo?></textarea>
</td>
</tr>
</tbody>
</table>
</div>
</div> <!-- end of card-body -->
</div> <!-- end of card -->
<div class="card align-middle">
<div class="card-body text-center">
<div class="d-flex p-1 mb-1 justify-content-start align-items-center ">
<span class="text-center badge bg-danger fs-6 me-1">기성청구</span>
<button type="button" id="claim_viewBtn" class="btn btn-danger btn-sm me-2"><i class="bi bi-chevron-down"></i></button>
<div id="claim_view" style="display: none;"> <!-- 최초에는 보이지 않도록 설정 -->
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">구분</th>
<th class="text-center">청구일</th>
<th class="text-center">청구금액</th>
<th class="text-center">확정금액</th>
<th class="text-center">잔액</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">1차</td>
<td><input type="date" name="claimdate1" value="<?=$claimdate1?>" class="form-control" placeholder="1차청구일" /></td>
<td><input type="text" name="claimamount1" value="<?=$claimamount1?>" class="form-control" placeholder="1차청구액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimfix1" value="<?=$claimfix1?>" class="form-control" placeholder="1차확정액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimbalance1" value="<?=$claimbalance1?>" class="form-control" placeholder="1차잔액" disabled /></td>
</tr>
<tr>
<td class="text-center">2차</td>
<td><input type="date" name="claimdate2" value="<?=$claimdate2?>" class="form-control" placeholder="2차청구일" /></td>
<td><input type="text" name="claimamount2" value="<?=$claimamount2?>" class="form-control" placeholder="2차청구액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimfix2" value="<?=$claimfix2?>" class="form-control" placeholder="2차확정액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimbalance2" value="<?=$claimbalance2?>" class="form-control" placeholder="2차잔액" disabled /></td>
</tr>
<tr>
<td class="text-center">3차</td>
<td><input type="date" name="claimdate3" value="<?=$claimdate3?>" class="form-control" placeholder="3차청구일" /></td>
<td><input type="text" name="claimamount3" value="<?=$claimamount3?>" class="form-control" placeholder="3차청구액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimfix3" value="<?=$claimfix3?>" class="form-control" placeholder="3차확정액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimbalance3" value="<?=$claimbalance3?>" class="form-control" placeholder="3차잔액" disabled /></td>
</tr>
<tr>
<td class="text-center">4차</td>
<td><input type="date" name="claimdate4" value="<?=$claimdate4?>" class="form-control" placeholder="4차청구일" /></td>
<td><input type="text" name="claimamount4" value="<?=$claimamount4?>" class="form-control" placeholder="4차청구액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimfix4" value="<?=$claimfix4?>" class="form-control" placeholder="4차확정액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimbalance4" value="<?=$claimbalance4?>" class="form-control" placeholder="4차잔액" disabled /></td>
</tr>
<tr>
<td class="text-center">5차</td>
<td><input type="date" name="claimdate5" value="<?=$claimdate5?>" class="form-control" placeholder="5차청구일" /></td>
<td><input type="text" name="claimamount5" value="<?=$claimamount5?>" class="form-control" placeholder="5차청구액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimfix5" value="<?=$claimfix5?>" class="form-control" placeholder="5차확정액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimbalance5" value="<?=$claimbalance5?>" class="form-control" placeholder="5차잔액" disabled /></td>
</tr>
<tr>
<td class="text-center">6차</td>
<td><input type="date" name="claimdate6" value="<?=$claimdate6?>" class="form-control" placeholder="6차청구일" /></td>
<td><input type="text" name="claimamount6" value="<?=$claimamount6?>" class="form-control" placeholder="6차청구액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimfix6" value="<?=$claimfix6?>" class="form-control" placeholder="6차확정액" onkeyup="inputNumberFormat(this); updateEstimate()" /></td>
<td><input type="text" name="claimbalance6" value="<?=$claimbalance6?>" class="form-control" placeholder="6차잔액" disabled /></td>
</tr>
<tr>
<td class="text-center"><b>누적계</b></td>
<td></td>
<td><input type="text" name="claimamount7" id="claimamount7" class="form-control" placeholder="청구금누계" disabled /></td>
<td><input type="text" name="claimfix7" id="claimfix7" class="form-control" placeholder="확정액누계" disabled /></td>
<td><input type="text" name="claimbalance7" id="claimbalance7" class="form-control" placeholder="잔액누계" disabled /></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div> <!-- end of col-sm-8 -->
<div class="card align-middle">
<div class="card-body text-center">
<div class="d-flex p-1 mb-1 justify-content-start align-items-center ">
<span class="text-center badge bg-dark fs-6 me-2"> AS</span>
<button type="button" id="as_viewBtn" class="btn btn-dark btn-sm me-2">
<i class="bi bi-chevron-down"></i>
</button>
<div id="as_view" style="display: none;"> <!-- 처음에는 보이지 않도록 설정 -->
<table class="table table-bordered">
<tbody>
<tr>
<td class="text-start" colspan="6">
<?php if($as_check != "1") { ?>
<input type="checkbox" name="as_check" value="1"> AS 진행현황만 표시
<?php } else { ?>
<input type="checkbox" name="as_check" checked value="1"> AS 진행현황만 표시
<?php } ?>
<button type="button" class="btn btn-dark btn-sm me-3" onclick='copy_below()'> AS기록 복사 이관 </button>
<button type="button" class="btn btn-dark btn-sm" onclick='del_below()'> 입력란 초기화 </button>
</td>
</tr>
<tr>
<td>AS 접수일</td>
<td><input type="date" id="asday" name="asday" class="form-control" value="<?=$asday?>" ></td>
<td>접수자</td>
<td><input type="text" id="aswriter" name="aswriter" class="form-control" value="<?=$aswriter?>" size="10" placeholder="AS접수자"></td>
<td>요청인</td>
<td><input type="text" id="asorderman" name="asorderman" class="form-control" value="<?=$asorderman?>" size="10" placeholder="AS의뢰자"></td>
</tr>
<tr>
<td colspan="1">
요청사항 선택
</td>
<td colspan="3">
<?php if($as_step == Null) $as_step="없음"; ?>
<input type="radio" name="as_step" value="없음" <?=$as_step == "없음" ? 'checked' : ''?>> 없음
<input type="radio" name="as_step" value="AS" <?=$as_step == "AS" ? 'checked' : ''?>> AS
<input type="radio" name="as_step" value="결선" <?=$as_step == "결선" ? 'checked' : ''?>> 결선
<input type="radio" name="as_step" value="입결선" <?=$as_step == "입결선" ? 'checked' : ''?>> 입결선
<input type="radio" name="as_step" value="셔터시공" <?=$as_step == "셔터시공" ? 'checked' : ''?>> 셔터시공
</td>
<td>연락처</td>
<td colspan="1"><input type="text" id="asordermantel" class="form-control" name="asordermantel" value="<?=$asordermantel?>" size="14" placeholder="요청인 연락처"></td>
</tr>
<tr>
<td colspan="6">
<?php if($asfee == 0) { ?>
무상 <input type="radio" id="asfee" checked name="asfee" value="0">
유상 <input type="radio" id="asfee" name="asfee" value="1" style="color:red">
<?php } else { ?>
무상 <input type="radio" id="asfee" name="asfee" value="0">
유상 <input type="radio" id="asfee" checked name="asfee" value="1" style="color:red">
<?php } ?>
유상일 경우 견적금액 : <input type="text" id="asfee_estimate" name="asfee_estimate" value="<?=$asfee_estimate?>" size="10" onkeyup="inputNumberFormat(this)" placeholder="유상 금액">
</td>
</tr>
<tr>
<td>AS 증상(구체적)</td>
<td colspan="2"><textarea rows="2" class="form-control" id="aslist" name="aslist" placeholder="구체적 증상 설명"><?=$aslist?></textarea></td>
<td>작업자 참조사항</td>
<td colspan="2"><textarea rows="2" class="form-control" id="as_refer" name="as_refer" placeholder="작업자 참조사항 기록"><?=$as_refer?></textarea></td>
</tr>
<tr>
<td>처리 예정일</td>
<td><input type="date" id="asproday" name="asproday" class="form-control" value="<?=$asproday?>" size="10" placeholder="AS 예정일" ></td>
<td>세팅 예정일</td>
<td><input type="date" id="setdate" name="setdate" class="form-control" value="<?=$setdate?>" size="10" placeholder="세팅 예정일" ></td>
<td>AS담당</td>
<td><input type="text" id="asman" name="asman" class="form-control" value="<?=$asman?>" size="10" placeholder="AS 처리담당"></td>
</tr>
<tr>
<td>최종AS완료</td>
<td><input type="date" id="asendday" name="asendday" class="form-control" value="<?=$asendday?>" ></td>
<td>
처리결과
</td>
<td colspan="4">
<textarea rows="2" id="asresult" name="asresult" class="form-control" placeholder="처리결과 기록"><?=$asresult?></textarea>
</td>
</tr>
<tr>
<td colspan="1">
AS 기록
</td>
<td colspan="5">
<textarea id="ashistory" rows="3" name="ashistory" class="form-control" placeholder="지속적으로 기록을 남겨 보관"><?=$ashistory?></textarea>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
});
var dataTable; // DataTables 인스턴스 전역 변수
var workpageNumber; // 현재 페이지 번호 저장을 위한 전역 변수
var mode = '<?php echo $mode; ?>';
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('workpageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
// 페이지 변경 이벤트 리스너
dataTable.on('page.dt', function() {
var workpageNumber = dataTable.page.info().page + 1;
setCookie('workpageNumber', workpageNumber, 10); // 쿠키에 페이지 번호 저장
});
// 페이지 길이 셀렉트 박스 변경 이벤트 처리
$('#myTable_length select').on('change', function() {
var selectedValue = $(this).val();
dataTable.page.len(selectedValue).draw(); // 페이지 길이 변경 (DataTable 파괴 및 재초기화 없이)
// 변경 후 현재 페이지 번호 복원
savedPageNumber = getCookie('workpageNumber');
if (savedPageNumber) {
dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
}
});
});
function restorePageNumber() {
var savedPageNumber = getCookie('workpageNumber');
// if (savedPageNumber) {
// dataTable.page(parseInt(savedPageNumber) - 1).draw('page');
// }
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
$("#saveBtn").click(function(){ // DATA 저장버튼 누름
var num = $("#num").val();
// 결재상신이 아닌경우 수정안됨
if(Number(num)>0)
$("#mode").val('modify');
else
$("#mode").val('insert');
// 자료 삽입/수정하는 모듈
saveData();
});
// 삭제버튼
$("#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());
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();
});
// 삽입/수정하는 모듈
function saveData() {
var form = $('#board_form')[0];
var data = new FormData(form);
// FormData의 내용을 디버그로 출력
// console.log("FormData before sending:");
// for (var pair of data.entries()) {
// console.log(pair[0] + ': ' + pair[1]);
// }
$("#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();
if ((typeof ajaxRequest_write !== 'undefined' && ajaxRequest_write) || ajaxRequest_write !== null) {
ajaxRequest_write.abort();
}
let accountList = [];
$('#accountListTable tbody tr').each(function() {
let rowData = {};
$(this).find('input').each(function() {
let name = $(this).attr('name').replace('[]', '');
rowData[name] = $(this).val();
});
accountList.push(rowData);
});
data.set('accountList', JSON.stringify(accountList));
let estimateList = [];
$('#estimateListTable tbody tr').each(function() {
let rowData = {};
let rowIndex = $(this).attr('data-index'); // 행의 인덱스 가져오기
rowData['row_index'] = rowIndex; // row_index 추가
$(this).find('input').each(function() {
let name = $(this).attr('name').replace('[]', '');
rowData[name] = $(this).val();
});
console.log("rowData['col5']", rowData['col5']);
console.log('name="col5[]', $(this).find('input[name="col5[]"]').val());
// 파일 처리
let fileInput = $(this).find('input[type="file"]');
if (fileInput.length > 0 && fileInput[0].files.length > 0) {
let file = fileInput[0].files[0];
data.append('upfile[]', file); // 파일을 FormData에 추가
data.append('row_index_for_upfile[]', rowIndex); // 해당 파일의 행 인덱스도 추가
rowData['col5'] = file.name; // col5에 파일 이름 추가
rowData['col6'] = ''; // col6은 서버에서 처리
console.log("file.name:", file.name);
} else {
// 파일이 선택되지 않았을 경우 기존의 col5, col6 값을 유지
rowData['col5'] = rowData['col5'] || $(this).find('input[name="col5[]"]').val();
rowData['col6'] = rowData['col6'] || $(this).find('input[name="col6[]"]').val();
}
estimateList.push(rowData);
});
data.set('estimateList', JSON.stringify(estimateList));
console.log("Estimate List:", estimateList);
ajaxRequest_write = $.ajax({
enctype: 'multipart/form-data', // file을 서버에 전송하려면 이렇게 해야 함 주의
processData: false,
contentType: false,
cache: false,
timeout: 600000,
url: "insert.php",
type: "post",
data: data,
dataType:"json",
success : function(data){
console.log('서버 응답:', data);
setTimeout(function() {
Toastify({
text: "저장완료",
duration: 3000,
close:true,
gravity:"top",
position: "center",
style: {
background: "linear-gradient(to right, #00b09b, #96c93d)"
},
}).showToast();
}, 1000);
setTimeout(function() {
if (data && data.num)
window.location.href = 'write_form.php?mode=view&tablename=' + $('#tablename').val() + '&num=' + data.num;
}, 1000);
hideOverlay();
},
error : function( jqxhr , status , error ){
console.log( jqxhr , status , error );
}
});
}
function displayFileName(input) {
var fileNameDisplay = $(input).closest('td').find('.file-name');
// 파일이 선택되었을 때 이름 표시
if (input.files && input.files.length > 0) {
var fileNames = Array.from(input.files).map(file => file.name).join(', ');
fileNameDisplay.text(fileNames);
} else {
fileNameDisplay.text(''); // 선택된 파일이 없으면 이름 표시 초기화
}
}
function updateEstimate() {
}
function updateTotals(totalEstimate=0) {
let totalClaimAmount = 0;
let totalClaimFix = 0;
let totalClaimBalance = totalEstimate;
for (let i = 1; i <= 6; i++) {
let claimAmount = document.querySelector(`input[name="claimamount${i}"]`).value.replace(/,/g, '');
let claimFix = document.querySelector(`input[name="claimfix${i}"]`).value.replace(/,/g, '');
claimAmount = claimAmount ? parseFloat(claimAmount) : 0;
claimFix = claimFix ? parseFloat(claimFix) : 0;
totalClaimAmount += claimAmount;
totalClaimFix += claimFix;
totalClaimBalance -= claimFix;
document.querySelector(`input[name="claimbalance${i}"]`).value = totalClaimBalance.toLocaleString();
}
document.getElementById('claimamount7').value = totalClaimAmount.toLocaleString();
document.getElementById('claimfix7').value = totalClaimFix.toLocaleString();
document.getElementById('claimbalance7').value = totalClaimBalance.toLocaleString();
// console.log(totalEstimate);
}
function adjustTextareaHeight(textarea) {
textarea.style.height = 'auto';
textarea.style.height = (textarea.scrollHeight) + 'px';
}
$(document).ready(function() {
var $accountnote = $('#accountnote');
if ($accountnote.length) {
adjustTextareaHeight($accountnote[0]); // 초기 높이 조정
$accountnote.on('input', function() {
adjustTextareaHeight(this);
});
}
var $comment = $('#comment');
if ($comment.length) {
adjustTextareaHeight($comment[0]); // 초기 높이 조정
$comment.on('input', function() {
adjustTextareaHeight(this);
});
}
var $outputmeno = $('#outputmeno');
if ($outputmeno.length) {
adjustTextareaHeight($outputmeno[0]); // 초기 높이 조정
$outputmeno.on('input', function() {
adjustTextareaHeight(this);
});
}
var $ashistory = $('#ashistory');
if ($ashistory.length) {
adjustTextareaHeight($ashistory[0]); // 초기 높이 조정
$ashistory.on('input', function() {
adjustTextareaHeight(this);
});
}
var $change_worklist = $('#change_worklist');
if ($change_worklist.length) {
adjustTextareaHeight($change_worklist[0]); // 초기 높이 조정
$change_worklist.on('input', function() {
adjustTextareaHeight(this);
});
}
var $worklist = $('#worklist');
if ($worklist.length) {
adjustTextareaHeight($worklist[0]); // 초기 높이 조정
$worklist.on('input', function() {
adjustTextareaHeight(this);
});
}
});
function calculateTotals() {
var totalSupply = 0;
var totalVAT = 0;
var totalBill = 0;
var totalDeposit = 0;
// accountListTable 테이블 내에서만 요소 선택 및 합계 계산
var table = document.getElementById('accountListTable');
table.querySelectorAll('input[name="col2[]"]').forEach(function(element) {
totalSupply += parseFloat(element.value.replace(/,/g, '') || 0);
});
table.querySelectorAll('input[name="col3[]"]').forEach(function(element) {
totalVAT += parseFloat(element.value.replace(/,/g, '') || 0);
});
table.querySelectorAll('input[name="col4[]"]').forEach(function(element) {
totalBill += parseFloat(element.value.replace(/,/g, '') || 0);
});
table.querySelectorAll('input[name="col6[]"]').forEach(function(element) {
totalDeposit += parseFloat(element.value.replace(/,/g, '') || 0);
});
var totalReceivable = totalBill - totalDeposit;
// 업데이트된 값을 합계 필드에 표시
document.getElementById('total_supply').value = numberWithCommas(totalSupply);
document.getElementById('total_vat').value = numberWithCommas(totalVAT);
document.getElementById('total_bill').value = numberWithCommas(totalBill);
document.getElementById('total_deposit').value = numberWithCommas(totalDeposit);
document.getElementById('total_receivable').textContent = numberWithCommas(totalReceivable);
// 숨겨진 필드에 계산된 합계 값을 설정
document.getElementById('sum_bill').value = totalBill.toFixed(2);
document.getElementById('sum_deposit').value = totalDeposit.toFixed(2);
document.getElementById('sum_receivable').value = totalReceivable.toFixed(2);
// 견적 테이블에서 마지막 견적 금액을 가져옴
var estimateTable = document.getElementById('estimateListTable');
var lastEstimateAmount = 0;
if (estimateTable) {
var estimateRows = estimateTable.querySelectorAll('input[name="col4[]"]');
if (estimateRows.length > 0) {
lastEstimateAmount = parseFloat(estimateRows[estimateRows.length - 1].value.replace(/,/g, '') || 0);
}
}
// 결정된 견적 업데이트
document.getElementById('decided_estimate').value = numberWithCommas(lastEstimateAmount);
// 발행합계(total_bill)의 값을 발행합계로 설정
var issuedAmount = totalBill;
document.getElementById('issued_amount').value = numberWithCommas(issuedAmount);
// 발행미수금 계산 및 업데이트 (decided_estimate - issued_amount)
var issuedReceivable = issuedAmount - totalDeposit;
document.getElementById('issued_receivable').value = numberWithCommas(issuedReceivable);
// 입금미수금 계산 및 업데이트 (issued_amount - total_deposit)
totalReceivable = lastEstimateAmount - totalDeposit;
document.getElementById('total_receivable').value = numberWithCommas(totalReceivable);
// 추가로 합계에 영향을 주는 항목이 있다면 여기에 추가
// 필요시 추가적인 숨겨진 필드 업데이트
document.getElementById('sum_receivable').value = totalReceivable.toFixed(2);
}
// 숫자를 콤마 형식으로 표시하는 함수
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// 페이지가 로드될 때 초기 계산 수행
document.addEventListener('DOMContentLoaded', function() {
calculateTotals();
});
// 특정 입력 필드 값이 변경될 때마다 합계를 다시 계산하도록 이벤트 리스너 추가
document.querySelectorAll('#decided_estimate, #issued_amount, #issued_receivable').forEach(function(element) {
element.addEventListener('input', calculateTotals);
});
// 입력값을 포맷하는 함수
function formatInput(input) {
var value = input.value.replace(/,/g, '');
if (!isNaN(value) && value !== '') {
input.value = numberWithCommas(parseFloat(value));
}
}
// 3자리마다 콤마를 추가하는 함수
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function inputNumberFormat(obj) {
// 숫자 및 - 이외의 문자는 제거
obj.value = obj.value.replace(/[^0-9-]/g, '');
// 콤마를 제거하고 숫자를 포맷팅
let value = obj.value.replace(/,/g, '');
// 부호가 앞에 오도록 함
if (value.startsWith('-')) {
value = '-' + value.slice(1).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} else {
value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
obj.value = value;
}
</script>
<script>
$(document).ready(function() {
var accountList = <?php echo json_encode($accountList ?? []); ?>;
var estimateList = <?php echo json_encode($estimateList ?? []); ?>;
// JSON이 배열인지 아닌지 여부를 확인하는 방법
if (typeof accountList === 'string') {
try {
accountList = JSON.parse(accountList);
} catch (e) {
console.error('JSON 파싱 오류:', e);
accountList = [];
}
}
if (Array.isArray(accountList)) {
console.log('accountList is an array:', accountList);
} else {
console.log('accountList is not an array, resetting to empty array');
accountList = [];
}
accountList.forEach(function(rowData, index) {
addRow_Bill($('#accountListBody'), rowData);
});
// JSON이 배열인지 아닌지 여부를 확인하는 방법
if (typeof estimateList === 'string') {
try {
estimateList = JSON.parse(estimateList);
} catch (e) {
console.error('JSON 파싱 오류:', e);
estimateList = [];
}
}
if (Array.isArray(estimateList)) {
console.log('estimateList is an array:', estimateList);
} else {
console.log('estimateList is not an array, resetting to empty array');
estimateList = [];
}
estimateList.forEach(function(rowData, index) {
addRow_Estimate($('#estimateListBody'), rowData);
});
// `upfile` 속성을 모두 제거
estimateList.forEach(function(item) {
delete item.upfile;
});
// 아래 코드를 사용하여 console에서 확인할 수 있습니다.
console.log('upfile제거후 ', estimateList);
// console.log('php json : ', accountList);
// Log 파일보기
$("#showlogBtn").click( function() {
var num = '<?php echo $num; ?>'
// table 이름을 넣어야 함
var workitem = 'work' ;
// 버튼 비활성화
var btn = $(this);
popupCenter("../Showlog.php?num=" + num + "&workitem=" + workitem , '로그기록', 500, 500);
btn.prop('disabled', false);
});
// 행 추가 시에도 일련번호를 업데이트 (삭제 버튼 이벤트 예시)
$(document).on('click', '.add-row', function() {
var tableId = $(this).data('table');
var tableBody = $('#' + tableId).find('tbody');
addRow_Bill(tableBody, {}, tableId);
updateSerialNumbers($('#accountListBody'));
calculateTotals();
});
$(document).on('click', '.remove-row', function() {
$(this).closest('tr').remove();
updateSerialNumbers($('#accountListBody'));
calculateTotals();
});
// 견적서에 대한 이벤트 처리
$(document).on('click', '.add-row-estimate', function() {
var tableBody = $('#' + $(this).data('table')).find('tbody');
addRow_Estimate(tableBody);
calculateTotals();
});
$(document).on('click', '.remove-row-estimate', function() {
$(this).closest('tr').remove();
updateSerialNumbers($('#estimateListTable').find('tbody'));
calculateTotals();
});
updateTotals();
calculateTotals(); // 초기 계산
});
function addRow_Bill(tableBody, rowData = {}) {
var newRow = $('<tr>');
if (rowData.col2 !== undefined && rowData.col2 !== null) {
rowData.col2 = numberWithCommas(rowData.col2);
}
if (rowData.col3 !== undefined && rowData.col3 !== null) {
rowData.col3 = numberWithCommas(rowData.col3);
}
if (rowData.col4 !== undefined && rowData.col4 !== null) {
rowData.col4 = numberWithCommas(rowData.col4);
}
if (rowData.col6 !== undefined && rowData.col6 !== null) {
rowData.col6 = numberWithCommas(rowData.col6);
}
// 첫 번째 열: 일련번호 (자동 생성)
newRow.append('<td class="text-center" style="width:80px;">' +
'<div class="d-flex justify-content-center align-items-center "> <span class="serial-number me-2"></span>' +
'<button type="button" class="btn btn-outline-primary btn-sm viewNoBtn add-row me-1" data-table="' + tableBody.closest('table').attr('id') + '">+</button>' +
'<button type="button" class="btn btn-outline-danger btn-sm viewNoBtn remove-row">-</button>' +
'</div></td>');
// col1 (발행일자) - "0000-00-00"을 빈 문자열로 처리
var col1Value = (rowData.col1 === "0000-00-00") ? '' : rowData.col1;
newRow.append('<td class="text-center"><input type="date" name="col1[]" class="form-control text-center" value="' + col1Value + '"></td>');
// col2 (공급가액) 및 계산 아이콘
newRow.append('<td class="text-center">' +
'<div class="d-flex align-items-center">' +
'<input type="text" name="col2[]" class="form-control text-end number-format me-1" placeholder="공급가액" onkeyup="inputNumberFormat(this);" value="' + (rowData.col2 || '') + '">' +
'<span class=" cursor-pointer" onclick="calculateBasedOnSupply($(this).closest(\'tr\'));">' +
'<i class="bi bi-calculator-fill"></i></span>' +
'</div></td>');
// col3 (부가세)
newRow.append('<td class="text-center"><input type="text" name="col3[]" class="form-control text-end number-format" placeholder="부가세" onkeyup="inputNumberFormat(this);" value="' + (rowData.col3 || '') + '"></td>');
// col4 (발행금액) 및 계산 아이콘
newRow.append('<td class="text-center">' +
'<div class="d-flex align-items-center">' +
'<input type="text" name="col4[]" class="form-control text-end number-format me-1" placeholder="발행금액" onkeyup="inputNumberFormat(this);" value="' + (rowData.col4 || '') + '">' +
'<span class="cursor-pointer" onclick="calculateBasedOnTotal($(this).closest(\'tr\'));">' +
'<i class="bi bi-calculator-fill"></i></span>' +
'</div></td>');
// col5 (입금일자) - "0000-00-00"을 빈 문자열로 처리
var col5Value = (rowData.col5 === "0000-00-00") ? '' : rowData.col5;
newRow.append('<td class="text-center"><input type="date" name="col5[]" class="form-control text-center" value="' + col5Value + '"></td>');
// col6 (입금액)
newRow.append('<td class="text-center"><input type="text" name="col6[]" class="form-control text-end number-format" placeholder="입금액" onkeyup="inputNumberFormat(this);" value="' + (rowData.col6 || '') + '"></td>');
tableBody.append(newRow);
// 일련번호를 업데이트
updateSerialNumbers(tableBody);
// 숫자 필드에 3자리마다 콤마 추가 (소수점 입력 가능)
newRow.find('.number-format').on('input change', function() {
let value = $(this).val().replace(/,/g, ''); // 기존의 콤마를 제거
// 소수점 포함 숫자 검사
if (!isNaN(value) && value !== '') {
// 정수와 소수 부분 분리
let parts = value.split('.');
parts[0] = Number(parts[0]).toLocaleString('en'); // 3자리마다 콤마 추가
// 소수점이 있는 경우
let formattedValue = parts.join('.');
$(this).val(formattedValue);
}
//계산 함수 호출
calculateTotals();
});
// 처음 로드될 때도 자동 계산 적용
calculateTotals();
}
function displayFileName(input) {
var fileNameDisplay = $(input).closest('td').find('.file-name');
// 파일이 선택되었을 때 이름 표시
if (input.files && input.files.length > 0) {
var fileNames = Array.from(input.files).map(file => file.name).join(', ');
fileNameDisplay.text(fileNames);
} else {
fileNameDisplay.text(''); // 선택된 파일이 없으면 이름 표시 초기화
}
}
function addRow_Estimate(tableBody, rowData = {}, index = null) {
if (rowData.col2 !== undefined && rowData.col2 !== null) {
rowData.col2 = numberWithCommas(rowData.col2);
}
if (rowData.col3 !== undefined && rowData.col3 !== null) {
rowData.col3 = numberWithCommas(rowData.col3);
}
if (rowData.col4 !== undefined && rowData.col4 !== null) {
rowData.col4 = numberWithCommas(rowData.col4);
}
var newRowIndex = index !== null ? index : tableBody.find('tr').length; // 고유 인덱스
var newRow = $('<tr>').attr('data-index', newRowIndex); // 인덱스를 행에 할당
// 첫 번째 열: 일련번호 (자동 생성)
newRow.append('<td class="text-center" style="width:8%;">' +
'<div class="d-flex justify-content-center align-items-center"> <span class="serial-number me-2"></span>' +
'<button type="button" class="btn btn-outline-primary btn-sm viewNoBtn add-row-estimate me-1" data-table="' + tableBody.closest('table').attr('id') + '">+</button>' +
'<button type="button" class="btn btn-outline-danger btn-sm viewNoBtn remove-row-estimate">-</button>' +
'</div></td>');
// col1 (견적일) - "0000-00-00"을 빈 문자열로 처리
var col1Value = (rowData.col1 === "0000-00-00") ? '' : rowData.col1;
newRow.append('<td class="text-center"><input type="date" name="col1[]" class="form-control text-center" value="' + col1Value + '"></td>');
// col2 (공급가액) 및 계산 아이콘
newRow.append('<td class="text-center">' +
'<div class="d-flex align-items-center">' +
'<input type="text" name="col2[]" class="form-control text-end number-format me-1" placeholder="공급가액" onkeyup="inputNumberFormat(this);" value="' + (rowData.col2 || '') + '">' +
'<span class="cursor-pointer" onclick="calculateBasedOnSupply($(this).closest(\'tr\'));">' +
'<i class="bi bi-calculator-fill"></i></span>' +
'</div></td>');
// col3 (부가세)
newRow.append('<td class="text-center"><input type="text" name="col3[]" class="form-control text-end number-format" placeholder="부가세" onkeyup="inputNumberFormat(this);" value="' + (rowData.col3 || '') + '"></td>');
// col4 (합계) 및 계산 아이콘
newRow.append('<td class="text-center">' +
'<div class="d-flex align-items-center">' +
'<input type="text" name="col4[]" class="form-control text-end number-format me-1" placeholder="합계" onkeyup="inputNumberFormat(this);" value="' + (rowData.col4 || '') + '">' +
'<span class="cursor-pointer" onclick="calculateBasedOnTotal($(this).closest(\'tr\'));">' +
'<i class="bi bi-calculator-fill"></i></span>' +
'</div></td>');
// col5 (첨부파일)
var fileColumnContent;
// 첨부파일 필드 생성 시 인덱스를 hidden input으로 추가
if (rowData.col5) {
fileColumnContent = '<a href="../uploads/' + (rowData.col6 || '#') + '" onclick="window.open(this.href,\'파일보기\',\'width=1400,height=800\'); return false;" style="color:blue;"><b>' + rowData.col5 + '</b></a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
'<input type="hidden" name="row_index[]" value="' + newRowIndex + '">' +
'<input type="hidden" name="col5[]" value="' + (rowData.col5 || '') + '"> ' +
'<input type="hidden" name="col6[]" value="' + (rowData.col6 || '') + '"> ' +
'<span class="text-danger me-2"> <i class="bi bi-trash3 fs-6"></i> </span> ' +
'<input type="checkbox" name="del_file[]" value="' + newRowIndex + '" class="me-1"> ';
} else {
fileColumnContent = '<label class="custom-file-upload">' +
'<input type="file" name="upfile[]" onchange="displayFileName(this)" data-row-index="' + newRowIndex + '">' +
'<input type="hidden" name="row_index[]" value="' + newRowIndex + '">' +
'<input type="hidden" name="col5[]" value="' + (rowData.col5 || '') + '"> ' +
'<input type="hidden" name="col6[]" value="' + (rowData.col6 || '') + '"> ' +
'<i class="bi bi-paperclip"></i>' +
'</label>' +
'<span class="file-name ms-2"></span>';
}
newRow.append('<td class="text-start">' +
'<div class="d-flex justify-content-start">' +
fileColumnContent +
'</div></td>');
tableBody.append(newRow);
// 일련번호를 업데이트
updateSerialNumbers(tableBody);
}
// 공급가액을 기준으로 부가세와 발행금액 계산
function calculateBasedOnSupply(row) {
var supply = parseFloat(row.find('input[name="col2[]"]').val().replace(/,/g, '')) || 0;
var vat = supply * 0.1; // 부가세 10%
var total = supply + vat;
row.find('input[name="col3[]"]').val(numberWithCommas(vat.toFixed(0))); // 부가세
row.find('input[name="col4[]"]').val(numberWithCommas(total.toFixed(0))); // 발행금액
calculateTotals();
}
// 발행금액을 기준으로 공급가액과 부가세 계산
function calculateBasedOnTotal(row) {
var total = parseFloat(row.find('input[name="col4[]"]').val().replace(/,/g, '')) || 0;
var supply = total / 1.1; // 공급가액 = 발행금액 / 1.1
var vat = total - supply; // 부가세 = 발행금액 - 공급가액
row.find('input[name="col2[]"]').val(numberWithCommas(supply.toFixed(0))); // 공급가액
row.find('input[name="col3[]"]').val(numberWithCommas(vat.toFixed(0))); // 부가세
calculateTotals();
}
// 일련번호 업데이트 함수
function updateSerialNumbers(tableBody) {
tableBody.find('tr').each(function(index) {
$(this).find('.serial-number').text(index + 1);
});
}
document.addEventListener("DOMContentLoaded", function() {
const claimViewBtn = document.getElementById("claim_viewBtn");
const claimView = document.getElementById("claim_view");
claimViewBtn.addEventListener("click", function() {
if (claimView.style.display === "none") {
claimView.style.display = "block";
} else {
claimView.style.display = "none";
}
});
// as 토글
const asViewBtn = document.getElementById("as_viewBtn");
const asView = document.getElementById("as_view");
asViewBtn.addEventListener("click", function() {
if (asView.style.display === "none" || asView.style.display === "") {
asView.style.display = "block";
} else {
asView.style.display = "none";
}
});
});
function copy_below(){
var park = document.getElementsByName("asfee");
document.getElementById("ashistory").value = document.getElementById("ashistory").value + document.getElementById("asday").value + " " + document.getElementById("aswriter").value+ " " + document.getElementById("asorderman").value + " ";
document.getElementById("ashistory").value = document.getElementById("ashistory").value + document.getElementById("asordermantel").value + " " ;
if(park[1].checked) {
document.getElementById("ashistory").value = document.getElementById("ashistory").value +" 유상 " + document.getElementById("asfee").value + " ";
}
else
{
document.getElementById("ashistory").value = document.getElementById("ashistory").value +" 무상 "+ document.getElementById("asfee").value + " ";
}
document.getElementById("ashistory").value += document.getElementById("asfee_estimate").value + " " + document.getElementById("aslist").value+ " " + document.getElementById("as_refer").value + " ";
document.getElementById("ashistory").value += document.getElementById("asproday").value + " " + document.getElementById("setdate").value+ " " + document.getElementById("asman").value + " ";
document.getElementById("ashistory").value += document.getElementById("asendday").value + " " + document.getElementById("asresult").value+ " ";
}
function del_below()
{
if(confirm("초기화한 자료는 복구할 방법이 없습니다.\n\n정말 초기화 하시겠습니까?")) {
document.getElementById("asday").value = "" ;
document.getElementById("aswriter").value = "" ;
document.getElementById("asorderman").value = "" ;
document.getElementById("asordermantel").value ="";
document.getElementById("asfee_estimate").value = "";
document.getElementById("aslist").value = "";
document.getElementById("as_refer").value ="";
document.getElementById("asproday").value ="";
document.getElementById("setdate").value =""
document.getElementById("asman").value = "";
document.getElementById("asendday").value = "";
document.getElementById("asresult").value = "";
}
}
function calculateWarrantyPeriod() {
const fromDate = new Date(document.getElementById('warrantyFromDate').value);
const toDate = new Date(document.getElementById('warrantyToDate').value);
if (!fromDate || !toDate || toDate < fromDate) {
document.getElementById('warrantyPeriod').value = '';
return;
}
let years = toDate.getFullYear() - fromDate.getFullYear();
let months = toDate.getMonth() - fromDate.getMonth();
if (months < 0) {
years--;
months += 12;
}
let period = '';
if (years > 0) period += years + '년';
if (months > 0) period += (years > 0 ? ' ' : '') + months + '개월';
if (period === '') period = ''; // 최소 1개월
document.getElementById('warrantyPeriod').value = period;
}
</script>
<!-- mode == 'view' 조회 화면일때 사용금지 시키는 구문 -->
<script>
$(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);
$('.viewNoBtn').prop('disabled', true);
}
var inputs = document.querySelectorAll('input');
inputs.forEach(function(input) {
input.setAttribute('autocomplete', 'off');
});
// 페이지가 로드될 때 처음으로 실행
calculateWarrantyPeriod();
// 두 날짜 필드에 이벤트 리스너를 추가하여 값이 변경될 때마다 실행
document.getElementById('warrantyFromDate').addEventListener('change', calculateWarrantyPeriod);
document.getElementById('warrantyToDate').addEventListener('change', calculateWarrantyPeriod);
});
</script>
</body>
</html>