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

677 lines
25 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';
$title_message = '전체 미수금';
?>
<title> <?=$title_message?> </title>
</head>
<body>
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/mymodal.php'); ?>
<?php
if($user_id === '0266771300' ) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader_accountant1.php'); // 경리
} else {
require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader1.php');
}
?>
<?php
$tablename = 'work';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();
// 검색 조건 설정
$find = isset($_REQUEST['find']) ? $_REQUEST['find'] : 'all';
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';
$fromdate = isset($_REQUEST['fromdate']) ? $_REQUEST['fromdate'] : '';
$todate = isset($_REQUEST['todate']) ? $_REQUEST['todate'] : '';
$SettingDate = isset($_REQUEST['SettingDate']) ? $_REQUEST['SettingDate'] : " regist_day ";
$work_status_radio = isset($_REQUEST['work_status_radio']) ? $_REQUEST['work_status_radio'] : "전체";
// 현재 날짜
$currentDate = date("Y-m-d");
// fromdate 또는 todate가 빈 문자열이거나 null인 경우
if ($fromdate === "" || $fromdate === null || $todate === "" || $todate === null) {
// $fromdate = date("Y-m-d", strtotime("-180 months", strtotime($currentDate))); // 10년 이전 날짜
$fromdate = date("Y-m-d", strtotime("2012-01-01")); // 10년 이전 날짜
$todate = $currentDate; // 현재 날짜
$Transtodate = $todate;
} else {
// fromdate와 todate가 모두 설정된 경우 (기존 로직 유지)
$Transtodate = $todate;
}
// print $SettingDate;
if($work_status_radio == '계약전') // checkbox = 1 인 자료
$statusStr = " And checkbox = '1' " ;
else if($work_status_radio !== '전체')
$statusStr = " And workStatus = '". $work_status_radio . "'" ;
else
$statusStr = '';
$common = $SettingDate . " between '$fromdate' and '$Transtodate' and is_deleted IS NULL " . $statusStr . "
AND (CAST(REPLACE(issued_receivable, ',', '') AS UNSIGNED) > 0
OR CAST(REPLACE(total_receivable, ',', '') AS UNSIGNED) > 0
OR CAST(REPLACE(total_receivable, ',', '') AS UNSIGNED) > 0)
AND CAST(REPLACE(total_receivable, ',', '') AS SIGNED) > 0";
// SQL 쿼리 작성
$orderby = " order by update_day desc, regist_day desc, num desc ";
$andPhrase= " and " . $common . $orderby ;
$wherePhrase= " where " . $common . $orderby ;
$sql = "SELECT * FROM $DB.$tablename " . $wherePhrase;
if (!empty($search)) {
$sql = "SELECT * FROM $DB.$tablename where searchtag LIKE '%$search%' " . $andPhrase ;
}
if ($find!=='all' && $search) {
$sql = "SELECT * FROM $DB.$tablename WHERE $find LIKE '%$search%' " . $andPhrase ;
}
try {
$stmh = $pdo->query($sql);
$total_row = $stmh->rowCount(); // 총 행 수 계산
} catch (PDOException $Exception) {
print "오류: " . $Exception->getMessage();
}
// print '$work_status_radio' . $work_status_radio;
// print '$sql' . $sql;
// 숫자에 콤마를 추가하는 함수
function formatNumberWithCommas($number) {
return number_format($number);
}
?>
<form id="board_form" name="board_form" method="post" action="accountlist.php?mode=search">
<input type="hidden" id="mode" name="mode" value="<?=$mode?>">
<input type="hidden" id="num" name="num">
<input type="hidden" id="tablename" name="tablename" value="<?=$tablename?>">
<input type="hidden" id="header" name="header" value="<?=$header?>">
<div class="container-fluid">
<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> &nbsp;&nbsp;&nbsp; &nbsp;
</div>
<div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-center align-items-center">
<i class="bi bi-caret-right"></i> <?= $total_row ?> 건 &nbsp; &nbsp;
&nbsp;
<!-- 기간부터 검색까지 연결 묶음 start -->
<span id="showdate" class="btn btn-dark btn-sm " > 기간 </span> &nbsp;
<div id="showframe" class="card">
<div class="card-header " style="padding:2px;">
<div class="d-flex justify-content-center align-items-center">
기간 설정
</div>
</div>
<div class="card-body">
<div class="d-flex justify-content-center align-items-center">
<button type="button" class="btn btn-outline-success btn-sm me-1 change_dateRange" onclick='alldatesearch()' > 전체 </button>
<button type="button" class="btn btn-dark btn-sm me-1 change_dateRange" onclick='yesterday()' > 전일 </button>
<button type="button" class="btn btn-outline-danger btn-sm me-1 change_dateRange" onclick='this_today()' > 오늘 </button>
<button type="button" class="btn btn-dark btn-sm me-1 change_dateRange" onclick='this_year()' > 당해년도 </button>
</div>
</div>
</div>
<input type="date" id="fromdate" name="fromdate" class="form-control" style="width:100px;" value="<?=$fromdate?>" > &nbsp; ~ &nbsp;
<input type="date" id="todate" name="todate" class="form-control me-1" style="width:100px;" value="<?=$todate?>" > &nbsp; </span>
<div class="inputWrap">
<input type="text" id="search" name="search" value="<?=$search?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off" class="form-control" style="width:150px;" > &nbsp;
<button class="btnClear"></button>
</div>
<div id="autocomplete-list">
</div>
&nbsp;
<button id="searchBtn" type="button" class="btn btn-dark btn-sm me-1" > <i class="bi bi-search"></i> 검색 </button>
</div>
<!-- <div class="d-flex p-1 m-1 mt-1 mb-1 justify-content-center align-items-center">
<div id="showstatusframe" class="card">
<div class="card-body">
<button type="button" class="btn btn-dark btn-sm " onclick="popupCenter('call_csv.php','CSV 파일추출',1600,500);"> 엑셀CSV</button>
</div>
</div>
</div>
-->
</div> <!--card-body-->
</div> <!--card -->
</div> <!--container-fluid -->
<div class="container-fluid">
<div class="d-flex justify-content-center align-items-center">
<table class="table table-hover" id="myTable">
<thead class="table-primary">
<tr>
<th class="text-center" style="width:40px;" >번호</th>
<th class="text-center" style="width:110px;">최근수정</th>
<th class="text-center" style="width:180px;">현장명</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:40px;" >시공</th>
<th class="text-center" style="width:40px;" >결선</th>
<th class="text-center" style="width:80px;" >견적</th>
<th class="text-center" style="width:80px;" >발행합계</th>
<th class="text-center" style="width:80px;" >입금합계</th>
<th class="text-center" style="width:80px;" >발행 미수금</th>
<th class="text-center" style="width:80px;" >총 미수금</th>
<th class="text-center" style="width:120px;">공사담당</th>
<th class="text-center" style="width:90px;" > <h6> <span class="badge bg-primary"> 입금약속일 </span> </h6> </th>
<th class="text-center" style="width:200px;">회계 메모</th>
</tr>
</thead>
<tbody>
<?php
$start_num = $total_row;
// 기존 코드 상단에 합계 변수 선언
$totalOverallEstimate = 0;
$totalOverallBill = 0;
$totalOverallDeposit = 0;
$totalOverallIssuedReceivable = 0;
$totalOverallReceivable = 0;
while ($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
include '_row.php';
// 콤마 제거 후 숫자로 변환
$decided_estimate = isset($row['decided_estimate']) ? str_replace(',', '', $row['decided_estimate']) : 0;
$issued_receivable = isset($row['issued_receivable']) ? str_replace(',', '', $row['issued_receivable']) : 0;
$issued_amount = isset($row['issued_amount']) ? str_replace(',', '', $row['issued_amount']) : 0;
$total_receivable = isset($row['total_receivable']) ? str_replace(',', '', $row['total_receivable']) : 0;
$total_deposit = isset($row['total_deposit']) ? str_replace(',', '', $row['total_deposit']) : 0;
// 합계 변수에 더하기
$totalOverallEstimate += $decided_estimate;
$totalOverallBill += $issued_amount;
$totalOverallDeposit += $total_deposit;
$totalOverallIssuedReceivable += $issued_receivable;
$totalOverallReceivable += $total_receivable;
// 포맷된 결과 출력
$decided_estimateFormatted = number_format($decided_estimate);
$issued_amountFormatted = number_format($issued_amount);
$issued_receivableFormatted = number_format($issued_receivable);
$total_depositFormatted = number_format($total_deposit);
$total_receivableFormatted = number_format($total_receivable);
$checkstep_str = "";
$promiseday = $promiseday == '0000-00-00' || empty($promiseday) ? '' : $promiseday;
// accountnote를 20글자까지만 자르고 넘는 경우 '...' 추가
$displayAccountNote = mb_strlen($accountnote) > 30 ? mb_substr($accountnote, 0, 30) . '...' : $accountnote;
// $workStatus에 대한 뱃지 클래스를 먼저 처리
switch ($workStatus) {
case '착공전':
$badge_class_work = 'badge bg-dark';
break;
case '시공중':
$badge_class_work = 'badge bg-primary';
break;
case '시공완료':
$badge_class_work = 'badge bg-danger';
break;
default:
$badge_class_work = 'badge bg-secondary';
break;
}
// $cableworkStatus에 대한 뱃지 클래스를 처리
switch ($cableworkStatus) {
case '결선중':
$badge_class_cable = 'badge bg-success';
break;
case '결선완료':
$badge_class_cable = 'badge bg-danger';
break;
default:
$badge_class_cable = 'badge bg-secondary';
break;
}
$displayworkplacename = mb_strlen($workplacename) > 20 ? mb_substr($workplacename, 0, 20) . '...' : $workplacename;
echo "<tr onclick=\"redirectToView('$num', '$tablename')\">
<td class='text-center'>{$start_num}</td>
<td class='text-center'>{$update_day}</td>
<td class='text-start'>{$displayworkplacename}</td>
<td class='text-center'>{$secondord}</td>
<td class='text-center'>{$secondordman}</td>
<td class='text-center'>{$secondordmantel}</td>
<td class='text-center'>
<span class='{$badge_class_work}'>" . htmlspecialchars($workStatus) . "</span>
</td>
<td class='text-center'>
<span class='{$badge_class_cable}'>" . htmlspecialchars($cableworkStatus) . "</span>
</td>
<td class='text-end'>{$decided_estimateFormatted}</td>
<td class='text-end'>{$issued_amountFormatted}</td>
<td class='text-end text-secondary'>{$total_depositFormatted}</td>
<td class='text-end text-primary '>{$issued_receivableFormatted}</td>
<td class='text-end text-danger '>{$total_receivableFormatted}</td>
<td class='text-start'>{$chargedperson}</td>
<td class='text-center fw-bold'>{$promiseday}</td>
<td class='text-start'>" . htmlspecialchars($displayAccountNote) . "</td>
</tr>";
$start_num--;
}
?>
</tbody>
<tfoot class='table-secondary'>
<tr>
<th class='text-center' colspan='6'>합계</th>
<th class='text-end'></th>
<th class='text-end'></th>
<th class='text-end ' style="margin:0px;padding:9px;"><?= number_format($totalOverallEstimate) ?></th>
<th class='text-end ' style="margin:0px;padding:9px;"><?= number_format($totalOverallBill) ?></th>
<th class='text-end ' style="margin:0px;padding:9px;"><?= number_format($totalOverallDeposit) ?></th>
<th class='text-end text-primary ' style="margin:0px;padding:9px;"><?= number_format($totalOverallIssuedReceivable) ?></th>
<th class='text-end text-danger ' style="margin:0px;padding:9px;"><?= number_format($totalOverallReceivable) ?></th>
<th class='text-end'></th>
<th class='text-end'></th>
</tr>
</tfoot>
</table>
</div>
</div> <!--container-->
</form>
</body>
</html>
<script>
// 페이지 로딩
$(document).ready(function(){
var loader = document.getElementById('loadingOverlay');
loader.style.display = 'none';
});
</script>
<script>
var dataTable; // DataTables 인스턴스 전역 변수
var workpageNumber; // 현재 페이지 번호 저장을 위한 전역 변수
$(document).ready(function() {
// DataTables 초기 설정
dataTable = $('#myTable').DataTable({
"paging": true,
"ordering": true,
"searching": true,
"pageLength": 500,
"lengthMenu": [100, 200, 500, 1000, 2000],
"language": {
"lengthMenu": "Show _MENU_ entries",
"search": "Live Search:"
},
"order": [[0, 'desc']] // 최근수정일
});
// 페이지 번호 복원 (초기 로드 시)
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);
}
function redirectToView(num, tablename) {
var url = "write_form.php?mode=view&num=" + num + "&tablename=" + tablename;
customPopup(url, '수주내역', 1850, 900);
}
$(document).ready(function(){
$("#writeBtn").click(function(){
var tablename = '<?php echo $tablename; ?>';
var url = "write_form.php?tablename=" + tablename;
customPopup(url, '수주', 1850, 900);
});
});
$(document).ready(function() {
// 쿠키에서 dateRange 값을 읽어와 셀렉트 박스에 반영
var savedDateRange = getCookie('motordateRange');
if (savedDateRange) {
$('#dateRange').val(savedDateRange);
}
// dateRange 셀렉트 박스 변경 이벤트 처리
$('#dateRange').on('change', function() {
var selectedRange = $(this).val();
var currentDate = new Date(); // 현재 날짜
var fromDate, toDate;
switch(selectedRange) {
case '최근3개월':
fromDate = new Date(currentDate.setMonth(currentDate.getMonth() - 3));
break;
case '최근6개월':
fromDate = new Date(currentDate.setMonth(currentDate.getMonth() - 6));
break;
case '최근1년':
fromDate = new Date(currentDate.setFullYear(currentDate.getFullYear() - 1));
break;
case '최근2년':
fromDate = new Date(currentDate.setFullYear(currentDate.getFullYear() - 2));
break;
case '직접설정':
fromDate = new Date(currentDate.setFullYear(currentDate.getFullYear() - 1));
break;
case '전체':
fromDate = new Date(currentDate.setFullYear(currentDate.getFullYear() - 20));
break;
default:
// 기본 값 또는 예외 처리
break;
}
// 날짜 형식을 YYYY-MM-DD로 변환
toDate = formatDate(new Date()); // 오늘 날짜
fromDate = formatDate(fromDate); // 계산된 시작 날짜
// input 필드 값 설정
$('#fromdate').val(fromDate);
$('#todate').val(toDate);
var selectedDateRange = $(this).val();
// 쿠키에 저장된 값과 현재 선택된 값이 다른 경우에만 페이지 새로고침
if (savedDateRange !== selectedDateRange) {
setCookie('motordateRange', selectedDateRange, 30); // 쿠키에 dateRange 저장
document.getElementById('board_form').submit();
}
});
});
function SearchEnter(){
if(event.keyCode == 13){
saveSearch();
}
}
function saveSearch() {
let searchInput = document.getElementById('search');
let searchValue = searchInput.value;
console.log('searchValue ' + searchValue);
if (searchValue === "") {
document.getElementById('board_form').submit();
} else {
let now = new Date();
let timestamp = now.toLocaleDateString() + ' ' + now.toLocaleTimeString();
let searches = getSearches();
// 기존에 동일한 검색어가 있는 경우 제거
searches = searches.filter(search => search.keyword !== searchValue);
// 새로운 검색 정보 추가
searches.unshift({ keyword: searchValue, time: timestamp });
searches = searches.slice(0, 15);
document.cookie = "searches=" + JSON.stringify(searches) + "; max-age=31536000";
var workpageNumber = 1;
setCookie('workpageNumber', workpageNumber, 10); // 쿠키에 페이지 번호 저장
// Set dateRange to '전체' and trigger the change event
$('#dateRange').val('전체').change();
document.getElementById('board_form').submit();
}
}
// 검색창에 쿠키를 이용해서 저장하고 화면에 보여주는 코드 묶음
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('search');
const autocompleteList = document.getElementById('autocomplete-list');
searchInput.addEventListener('input', function() {
const val = this.value;
let searches = getSearches();
let matches = searches.filter(s => {
if (typeof s.keyword === 'string') {
return s.keyword.toLowerCase().includes(val.toLowerCase());
}
return false;
});
renderAutocomplete(matches);
});
searchInput.addEventListener('focus', function() {
let searches = getSearches();
renderAutocomplete(searches);
console.log(searches);
});
});
var isMouseOverSearch = false;
var isMouseOverAutocomplete = false;
document.getElementById('search').addEventListener('focus', function() {
isMouseOverSearch = true;
showAutocomplete();
});
document.getElementById('search').addEventListener('blur', function() {
setTimeout(function() {
if (!isMouseOverAutocomplete) {
hideAutocomplete();
}
}, 100); // Delay of 100 milliseconds
});
function hideAutocomplete() {
document.getElementById('autocomplete-list').style.display = 'none';
}
function showAutocomplete() {
document.getElementById('autocomplete-list').style.display = 'block';
}
function renderAutocomplete(matches) {
const autocompleteList = document.getElementById('autocomplete-list');
// Remove all .autocomplete-item elements
const items = autocompleteList.getElementsByClassName('autocomplete-item');
while(items.length > 0){
items[0].parentNode.removeChild(items[0]);
}
matches.forEach(function(match) {
let div = document.createElement('div');
div.className = 'autocomplete-item';
div.innerHTML = '<span class="text-primary">' + match.keyword + ' </span>';
div.addEventListener('click', function() {
document.getElementById('search').value = match.keyword;
autocompleteList.innerHTML = '';
console.log(match.keyword);
document.getElementById('board_form').submit();
});
autocompleteList.appendChild(div);
});
}
function getSearches() {
let cookies = document.cookie.split('; ');
for (let cookie of cookies) {
if (cookie.startsWith('searches=')) {
try {
let searches = JSON.parse(cookie.substring(9));
// 배열이 50개 이상의 요소를 포함하는 경우 처음 50개만 반환
if (searches.length > 15) {
return searches.slice(0, 15);
}
return searches;
} catch (e) {
console.error('Error parsing JSON from cookies', e);
return []; // 오류가 발생하면 빈 배열 반환
}
}
}
return []; // 'searches' 쿠키가 없는 경우 빈 배열 반환
}
$(document).ready(function(){
$("#denkriModel").hover(function(){
$("#customTooltip").show();
}, function(){
$("#customTooltip").hide();
});
$("#searchBtn").click(function(){
saveSearch();
});
});
$(document).ready(function() {
$('.search-condition').change(function() {
// 모든 체크박스의 선택을 해제합니다.
$('.search-condition').not(this).prop('checked', false);
// 선택된 체크박스의 값으로 `check` 필드를 업데이트합니다.
var condition = $(this).is(":checked") ? $(this).val() : '';
$("#check").val(condition);
// 검색 입력란을 비우고 폼을 제출합니다.
// $("#search").val('');
$('#board_form').submit();
});
});
$(document).ready(function(){
// showstatus 요소와 showstatusframe 요소가 페이지에 존재하는지 확인
var showstatus = document.getElementById('showstatus');
var showstatusframe = document.getElementById('showstatusframe');
// 요소가 존재하지 않으면 나머지 코드는 실행하지 않음
if (!showstatus || !showstatusframe) {
return;
}
var hideTimeoutstatus; // 프레임을 숨기기 위한 타이머 변수
// 요소가 존재한다면 이벤트 리스너를 추가
showstatus.addEventListener('mouseenter', function(event) {
clearTimeout(hideTimeoutstatus); // 이미 설정된 타이머가 있다면 취소
showstatusframe.style.top = (showstatus.offsetTop + showstatus.offsetHeight) + 'px';
showstatusframe.style.left = showstatus.offsetLeft + 'px';
showstatusframe.style.display = 'block';
});
showstatus.addEventListener('mouseleave', startstatusHideTimer);
showstatusframe.addEventListener('mouseenter', function() {
clearTimeout(hideTimeoutstatus); // 이미 설정된 타이머가 있다면 취소
});
showstatusframe.addEventListener('mouseleave', startstatusHideTimer);
// 타이머를 시작하는 함수
function startstatusHideTimer() {
hideTimeoutstatus = setTimeout(function() {
showstatusframe.style.display = 'none';
}, 50); // 300ms 후에 프레임을 숨깁니다.
}
});
</script>
<script>
$(document).ready(function() {
// select 요소의 값이 변경될 때 폼 제출
$('#SettingDate').on('change', function() {
$('#board_form').submit();
});
// 라디오 버튼 클릭 시 폼 제출
$('input[type=radio][name=work_status_radio]').on('change', function() {
$('#board_form').submit();
});
});
$(document).ready(function(){
// 방문기록 남김
var title_message = '<?php echo $title_message ; ?>';
saveMenuLog(title_message);
});
</script>