1 Commits

Author SHA1 Message Date
f22e5922a2 웹페이지 형식으로 데이터를 추출할 수 있는 기능 2025-07-21 17:37:35 +09:00
4 changed files with 481 additions and 0 deletions

131
app/app.py Normal file
View File

@ -0,0 +1,131 @@
import os, sys
from flask import Flask, render_template, request, jsonify
from sqlalchemy import select, func, between, and_, or_
from datetime import datetime, timedelta
import json
# 경로 추가
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from conf import db, db_schema
app = Flask(__name__)
engine = db.engine
pos_table = db_schema.pos
@app.route('/')
def index():
today = datetime.today().date()
end_date = today - timedelta(days=1)
start_date = end_date - timedelta(days=6)
return render_template('index.html', start_date=start_date, end_date=end_date)
@app.route('/api/ca01_list')
def ca01_list():
with engine.connect() as conn:
result = conn.execute(
select(pos_table.c.ca01).distinct().order_by(pos_table.c.ca01)
).scalars().all()
return jsonify(['전체'] + result)
@app.route('/api/ca03_list')
def ca03_list():
ca01 = request.args.get('ca01', None)
with engine.connect() as conn:
query = select(pos_table.c.ca03).distinct().order_by(pos_table.c.ca03)
if ca01 and ca01 != '전체':
query = query.where(pos_table.c.ca01 == ca01)
result = conn.execute(query).scalars().all()
return jsonify(['전체'] + result)
@app.route('/search', methods=['GET'])
def search():
start_date = request.args.get('start_date')
end_date = request.args.get('end_date')
ca01 = request.args.get('ca01')
ca03 = request.args.get('ca03')
conditions = [between(pos_table.c.date, start_date, end_date)]
if ca01 and ca01 != '전체':
conditions.append(pos_table.c.ca01 == ca01)
if ca03 and ca03 != '전체':
conditions.append(pos_table.c.ca03 == ca03)
with engine.connect() as conn:
stmt = select(
pos_table.c.ca01,
pos_table.c.ca02,
pos_table.c.ca03,
pos_table.c.name,
func.sum(pos_table.c.qty).label("qty"),
func.sum(pos_table.c.tot_amount).label("tot_amount"),
func.sum(pos_table.c.tot_discount).label("tot_discount"),
func.sum(pos_table.c.actual_amount).label("actual_amount")
).where(*conditions).group_by(pos_table.c.barcode)
result = conn.execute(stmt).mappings().all()
return jsonify([dict(row) for row in result])
# 월별 데이터 불러오기
def get_monthly_visitor_data(ca01_keywords=None, ca03_includes=None):
from collections import defaultdict
from decimal import Decimal
ca01_keywords = ca01_keywords or ['매표소']
ca03_includes = ca03_includes or ['입장료', '티켓', '기업제휴']
pos = db_schema.pos
session = db.get_session()
# 필터 조건
ca01_conditions = [pos.c.ca01.like(f'%{kw}%') for kw in ca01_keywords]
conditions = [or_(*ca01_conditions), pos.c.ca03.in_(ca03_includes)]
# 연도별 월별 합계 쿼리
query = (
session.query(
func.year(pos.c.date).label('year'),
func.month(pos.c.date).label('month'),
func.sum(pos.c.qty).label('qty')
)
.filter(and_(*conditions))
.group_by(func.year(pos.c.date), func.month(pos.c.date))
.order_by(func.year(pos.c.date), func.month(pos.c.date))
)
result = query.all()
session.close()
# 결과 가공: {년도: [1~12월 값]} 형태
data = defaultdict(lambda: [0]*12)
for row in result:
year = int(row.year)
month = int(row.month)
qty = int(row.qty or 0) if isinstance(row.qty, Decimal) else row.qty or 0
data[year][month - 1] = qty
# Dict → 일반 dict 정렬
return dict(sorted(data.items()))
@app.route('/monthly_view.html')
def monthly_view():
visitor_data = get_monthly_visitor_data()
visitor_data_json = json.dumps(visitor_data) # JSON 문자열로 변환
return render_template('monthly_view.html', visitor_data=visitor_data_json)
from lib.weekly_visitor_forecast_prophet import get_forecast_dict
from lib.weekly_visitor_forecast import get_recent_dataframe, get_last_year_dataframe
@app.route('/2weeks_view')
def view_2weeks():
df_recent = get_recent_dataframe()
df_prev = get_last_year_dataframe()
return render_template(
'2weeks_view.html',
recent_data=df_recent.to_dict(orient='records'),
lastyear_data=df_prev.to_dict(orient='records')
)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')

61
app/templates/2weeks.html Normal file
View File

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>월별 입장객 현황</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="p-4">
<section class="2weeks_visitor_detail">
<h2>직전 2주간 방문객 현황 상세 내역</h2>
<table class="table table-bordered text-center align-middle">
<thead>
<tr>
<th colspan="2">구분</th>
<th colspan="{{ dates|length }}">방문현황</th>
<th rowspan="2">합계/평균</th>
<th colspan="3">예상</th>
</tr>
<tr>
<th>년도</th>
<th>항목</th>
{% for d in dates %}
<th>{{ d.strftime('%-m/%-d') }}</th>
{% endfor %}
<th>1일</th>
<th>2일</th>
<th>3일</th>
</tr>
</thead>
<tbody>
{% for year_label, data_by_item in data.items() %}
{% set rowspan_val = data_by_item|length %}
{% for item_name, row in data_by_item.items() %}
<tr>
{% if loop.first %}
<th rowspan="{{ rowspan_val }}">{{ year_label }}</th>
{% endif %}
<th>{{ item_name }}</th>
{% for val in row.values_list %}
<td>{{ val }}</td>
{% endfor %}
<td>{{ row.total or '' }}</td>
{% if row.expected %}
{% for ex_val in row.expected %}
<td>{{ ex_val }}</td>
{% endfor %}
{% else %}
<td colspan="3"></td>
{% endif %}
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
</section>
</body>
</html>

145
app/templates/index.html Normal file
View File

@ -0,0 +1,145 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>POS 데이터 조회</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="p-4">
<h2>POS 데이터 조회</h2>
<form id="filterForm" class="row g-3">
<div class="col-md-3">
<label>시작일</label>
<input type="date" name="start_date" value="{{ start_date }}" class="form-control">
</div>
<div class="col-md-3">
<label>종료일</label>
<input type="date" name="end_date" value="{{ end_date }}" class="form-control">
</div>
<div class="col-md-2">
<label>대분류</label>
<select name="ca01" class="form-select">
<option value="전체">전체</option>
</select>
</div>
<div class="col-md-2">
<label>소분류</label>
<select name="ca03" class="form-select">
<option value="전체">전체</option>
</select>
</div>
<div class="col-md-2 align-self-end">
<button type="submit" class="btn btn-primary w-100">조회</button>
</div>
</form>
<hr>
<table class="table table-bordered mt-3" id="resultTable">
<thead>
<tr>
<th>대분류</th><th>중분류</th><th>소분류</th><th>상품명</th>
<th>수량</th><th>총매출액</th><th>총할인액</th><th>실매출액</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th colspan="4" class="text-end">합계</th>
<th id="sum_qty">0</th>
<th id="sum_tot_amount">0</th>
<th id="sum_tot_discount">0</th>
<th id="sum_actual_amount">0</th>
</tr>
</tfoot>
</table>
<script>
async function fetchAndFillSelect(url, selectElem) {
const res = await fetch(url);
const list = await res.json();
selectElem.innerHTML = '';
list.forEach(val => {
const opt = document.createElement('option');
opt.value = val;
opt.textContent = val;
selectElem.appendChild(opt);
});
}
document.addEventListener('DOMContentLoaded', async () => {
const ca01Select = document.querySelector('select[name="ca01"]');
const ca03Select = document.querySelector('select[name="ca03"]');
// 대분류 목록 불러오기
await fetchAndFillSelect('/api/ca01_list', ca01Select);
// 대분류 변경 시 소분류 목록 갱신
ca01Select.addEventListener('change', async () => {
const selectedCa01 = ca01Select.value;
await fetchAndFillSelect(`/api/ca03_list?ca01=${encodeURIComponent(selectedCa01)}`, ca03Select);
});
// 초기 소분류 목록 불러오기
await fetchAndFillSelect('/api/ca03_list', ca03Select);
// 폼 제출 이벤트 처리
document.getElementById('filterForm').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(this);
const params = new URLSearchParams(formData);
const res = await fetch('/search?' + params.toString());
if (!res.ok) {
alert('조회 중 오류가 발생했습니다.');
return;
}
const data = await res.json();
const tbody = document.querySelector('#resultTable tbody');
tbody.innerHTML = '';
// 합계 초기화
let sum_qty = 0;
let sum_tot_amount = 0;
let sum_tot_discount = 0;
let sum_actual_amount = 0;
if (data.length === 0) {
tbody.innerHTML = `<tr><td colspan="8" class="text-center">조회 결과가 없습니다.</td></tr>`;
} else {
data.forEach(row => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${row.ca01}</td>
<td>${row.ca02}</td>
<td>${row.ca03}</td>
<td>${row.name}</td>
<td>${row.qty}</td>
<td>${row.tot_amount}</td>
<td>${row.tot_discount}</td>
<td>${row.actual_amount}</td>
`;
tbody.appendChild(tr);
// 합계 계산
sum_qty += Number(row.qty) || 0;
sum_tot_amount += Number(row.tot_amount) || 0;
sum_tot_discount += Number(row.tot_discount) || 0;
sum_actual_amount += Number(row.actual_amount) || 0;
});
}
// 합계 출력
document.getElementById('sum_qty').textContent = sum_qty.toLocaleString();
document.getElementById('sum_tot_amount').textContent = sum_tot_amount.toLocaleString();
document.getElementById('sum_tot_discount').textContent = sum_tot_discount.toLocaleString();
document.getElementById('sum_actual_amount').textContent = sum_actual_amount.toLocaleString();
});
});
</script>
</body>
</html>

View File

@ -0,0 +1,144 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>월별 입장객 현황</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.diff-positive { color: blue; }
.diff-negative { color: red; }
.diff-zero { color: gray; }
table th, table td { vertical-align: middle; }
table th { text-align: center; }
table td { text-align: right; } /* 숫자 우측 정렬 */
#visitorChart {
width: 90% ;
max-width: 1200px;
min-height: 600px;
margin: 30px auto;
}
</style>
</head>
<body class="p-4">
<h2>월별 입장객 현황 (2017년 ~ 현재)</h2>
<table class="table table-bordered table-sm">
<thead class="table-secondary">
<tr>
<th>연도</th>
<th>1월</th><th>2월</th><th>3월</th><th>4월</th><th>5월</th><th>6월</th>
<th>7월</th><th>8월</th><th>9월</th><th>10월</th><th>11월</th><th>12월</th>
<th>합계</th>
</tr>
</thead>
<tbody id="dataBody">
<!-- 데이터가 여기에 삽입됩니다 -->
</tbody>
</table>
<canvas id="visitorChart"></canvas>
<script>
const visitorData = JSON.parse('{{ visitor_data | safe }}');
function formatNumber(num) {
return num.toLocaleString('ko-KR');
}
function formatDiff(diff) {
if (diff > 0) return `<span class="diff-positive">(+${formatNumber(diff)})</span>`;
else if (diff < 0) return `<span class="diff-negative">(${formatNumber(diff)})</span>`;
else return `<span class="diff-zero">(0)</span>`;
}
function renderTable(data) {
const years = Object.keys(data).sort();
const tbody = document.getElementById('dataBody');
tbody.innerHTML = '';
years.forEach((year, idx) => {
const currYearData = data[year];
const prevYearData = idx > 0 ? data[years[idx-1]] : null;
let row = `<tr><th style="text-align:center">${year}</th>`;
let annualSum = 0;
for(let m=0; m<12; m++) {
const curr = currYearData[m] || 0;
annualSum += curr;
let diff = prevYearData ? (curr - (prevYearData[m] || 0)) : 0;
row += `<td>${formatNumber(curr)}<br>${formatDiff(diff)}</td>`;
}
row += `<th style="text-align:right">${formatNumber(annualSum)}</th></tr>`;
tbody.insertAdjacentHTML('beforeend', row);
});
}
function renderChart(data) {
const ctx = document.getElementById('visitorChart').getContext('2d');
const labels = ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'];
// 연도를 숫자형으로 정렬
const years = Object.keys(data).map(Number).sort((a, b) => a - b);
// 각 연도별 데이터셋 생성
const datasets = years.map((year, i) => ({
label: year.toString(),
data: data[year],
backgroundColor: `hsla(${(i * 40) % 360}, 70%, 50%, 0.7)`,
borderColor: `hsla(${(i * 40) % 360}, 70%, 50%, 1)`,
borderWidth: 1
}));
const chartData = {
labels: labels,
datasets: datasets
};
new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '입장객 수'
},
ticks: {
callback: value => value.toLocaleString('ko-KR')
}
}
},
plugins: {
legend: {
position: 'top'
},
title: {
display: true,
text: '월별 입장객 수 (연도별)'
},
tooltip: {
callbacks: {
label: context => `입장객 수: ${context.parsed.y.toLocaleString('ko-KR')}`
}
}
}
}
});
}
document.addEventListener('DOMContentLoaded', () => {
renderTable(visitorData);
renderChart(visitorData);
});
</script>
</body>
</html>