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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sqlite3
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from datetime import date, datetime, timedelta
|
| 5 |
+
import random
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import streamlit as st
|
| 9 |
+
from openpyxl import Workbook
|
| 10 |
+
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
|
| 11 |
+
from openpyxl.utils import get_column_letter
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# =========================================================
|
| 15 |
+
# Client Center 연동형 통합 상담일지 생성기
|
| 16 |
+
# - 기관유형별 버튼
|
| 17 |
+
# - 종사자상담 / 수급자상담 / 보호자상담 / 기타상담
|
| 18 |
+
# - Client Center SQLite 연동
|
| 19 |
+
# - 상담기록 DB 저장
|
| 20 |
+
# - 욕구사정 등 연장기한 알림
|
| 21 |
+
# - 평가 적합도 / 부족 항목 / 보호자 의견 / 상태변화 반영 점검
|
| 22 |
+
# - 엑셀 다운로드 (우측 상단 결재라인, A4 최적화, 선 잘림 방지)
|
| 23 |
+
# =========================================================
|
| 24 |
+
|
| 25 |
+
st.set_page_config(
|
| 26 |
+
page_title="통합 상담일지",
|
| 27 |
+
page_icon="📝",
|
| 28 |
+
layout="wide"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 32 |
+
|
| 33 |
+
DB_CANDIDATES = [
|
| 34 |
+
os.path.join(CURRENT_DIR, "data", "clients.db"),
|
| 35 |
+
os.path.join(CURRENT_DIR, "..", "Client Center", "data", "clients.db"),
|
| 36 |
+
os.path.join(CURRENT_DIR, "..", "ClientCenter", "data", "clients.db"),
|
| 37 |
+
os.path.join(CURRENT_DIR, "..", "Client_Center", "data", "clients.db"),
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
DB_PATH = None
|
| 41 |
+
for path in DB_CANDIDATES:
|
| 42 |
+
if os.path.exists(path):
|
| 43 |
+
DB_PATH = path
|
| 44 |
+
break
|
| 45 |
+
|
| 46 |
+
if DB_PATH is None:
|
| 47 |
+
os.makedirs(os.path.join(CURRENT_DIR, "data"), exist_ok=True)
|
| 48 |
+
DB_PATH = os.path.join(CURRENT_DIR, "data", "clients.db")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# -----------------------------
|
| 52 |
+
# 디자인
|
| 53 |
+
# -----------------------------
|
| 54 |
+
st.markdown(
|
| 55 |
+
"""
|
| 56 |
+
<style>
|
| 57 |
+
.block-container { padding-top: 2rem; }
|
| 58 |
+
.hero {
|
| 59 |
+
background: linear-gradient(135deg, #2E7D32, #66BB6A);
|
| 60 |
+
padding: 30px;
|
| 61 |
+
border-radius: 22px;
|
| 62 |
+
text-align: center;
|
| 63 |
+
margin-bottom: 22px;
|
| 64 |
+
}
|
| 65 |
+
.hero h1 { color: white; margin: 0; font-size: 36px; }
|
| 66 |
+
.hero p { color: white; margin-top: 10px; font-size: 18px; }
|
| 67 |
+
.notice {
|
| 68 |
+
background: #fff8e1;
|
| 69 |
+
border-left: 7px solid #f9a825;
|
| 70 |
+
padding: 15px;
|
| 71 |
+
border-radius: 12px;
|
| 72 |
+
margin-bottom: 18px;
|
| 73 |
+
}
|
| 74 |
+
.okbox {
|
| 75 |
+
background: #e8f5e9;
|
| 76 |
+
border-left: 7px solid #43a047;
|
| 77 |
+
padding: 14px;
|
| 78 |
+
border-radius: 12px;
|
| 79 |
+
margin-bottom: 14px;
|
| 80 |
+
}
|
| 81 |
+
.warnbox {
|
| 82 |
+
background: #fff3e0;
|
| 83 |
+
border-left: 7px solid #fb8c00;
|
| 84 |
+
padding: 14px;
|
| 85 |
+
border-radius: 12px;
|
| 86 |
+
margin-bottom: 14px;
|
| 87 |
+
}
|
| 88 |
+
</style>
|
| 89 |
+
""",
|
| 90 |
+
unsafe_allow_html=True,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
st.markdown(
|
| 94 |
+
"""
|
| 95 |
+
<div class="hero">
|
| 96 |
+
<h1>📝 통합 상담일지 생성기</h1>
|
| 97 |
+
<p>Client Center 수급자 정보와 연동하여 기관유형별 상담기록을 생성·저장·점검합니다.</p>
|
| 98 |
+
</div>
|
| 99 |
+
""",
|
| 100 |
+
unsafe_allow_html=True,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
st.markdown(
|
| 104 |
+
"""
|
| 105 |
+
<div class="notice">
|
| 106 |
+
<strong>구성:</strong> 기관유형 버튼 → 상담분류 선택 → 수급자 정보 자동 불러오기 → 상담일지 생성 → 평가 적합도 점검 → 엑셀 다운로드 / 상담기록 저장
|
| 107 |
+
</div>
|
| 108 |
+
""",
|
| 109 |
+
unsafe_allow_html=True,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# -----------------------------
|
| 114 |
+
# DB 함수
|
| 115 |
+
# -----------------------------
|
| 116 |
+
def get_conn():
|
| 117 |
+
return sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 118 |
+
|
| 119 |
+
def init_db():
|
| 120 |
+
conn = get_conn()
|
| 121 |
+
cur = conn.cursor()
|
| 122 |
+
|
| 123 |
+
cur.execute(
|
| 124 |
+
"""
|
| 125 |
+
CREATE TABLE IF NOT EXISTS clients (
|
| 126 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 127 |
+
name TEXT NOT NULL,
|
| 128 |
+
masked_name TEXT,
|
| 129 |
+
gender TEXT,
|
| 130 |
+
birth_year TEXT,
|
| 131 |
+
care_grade TEXT,
|
| 132 |
+
institution_type TEXT,
|
| 133 |
+
institution_name TEXT,
|
| 134 |
+
admission_date TEXT,
|
| 135 |
+
main_condition TEXT,
|
| 136 |
+
cognitive_status TEXT,
|
| 137 |
+
mobility_status TEXT,
|
| 138 |
+
diet_status TEXT,
|
| 139 |
+
toileting_status TEXT,
|
| 140 |
+
guardian_name TEXT,
|
| 141 |
+
guardian_phone TEXT,
|
| 142 |
+
notes TEXT,
|
| 143 |
+
status TEXT DEFAULT '이용중',
|
| 144 |
+
created_at TEXT,
|
| 145 |
+
updated_at TEXT
|
| 146 |
+
)
|
| 147 |
+
"""
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Client Center 최종 필드 추가
|
| 151 |
+
new_columns = {
|
| 152 |
+
"recognition_number": "TEXT",
|
| 153 |
+
"recognition_start_date": "TEXT",
|
| 154 |
+
"recognition_end_date": "TEXT",
|
| 155 |
+
"previous_care_grade": "TEXT",
|
| 156 |
+
"plan_change_required": "TEXT DEFAULT '아니오'",
|
| 157 |
+
"plan_change_type": "TEXT",
|
| 158 |
+
"plan_change_reason": "TEXT",
|
| 159 |
+
"plan_change_date": "TEXT",
|
| 160 |
+
"plan_rewrite_status": "TEXT DEFAULT '해당없음'",
|
| 161 |
+
"linked_document": "TEXT",
|
| 162 |
+
}
|
| 163 |
+
cur.execute("PRAGMA table_info(clients)")
|
| 164 |
+
existing_cols = [row[1] for row in cur.fetchall()]
|
| 165 |
+
for col, col_type in new_columns.items():
|
| 166 |
+
if col not in existing_cols:
|
| 167 |
+
cur.execute(f"ALTER TABLE clients ADD COLUMN {col} {col_type}")
|
| 168 |
+
|
| 169 |
+
cur.execute(
|
| 170 |
+
"""
|
| 171 |
+
CREATE TABLE IF NOT EXISTS counseling_records (
|
| 172 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 173 |
+
client_id INTEGER,
|
| 174 |
+
client_masked_name TEXT,
|
| 175 |
+
institution_type TEXT,
|
| 176 |
+
counseling_type TEXT,
|
| 177 |
+
counseling_date TEXT,
|
| 178 |
+
counselor TEXT,
|
| 179 |
+
counseling_reason TEXT,
|
| 180 |
+
client_status_change TEXT,
|
| 181 |
+
guardian_opinion TEXT,
|
| 182 |
+
counseling_content TEXT,
|
| 183 |
+
action_plan TEXT,
|
| 184 |
+
evaluation_score INTEGER,
|
| 185 |
+
missing_items TEXT,
|
| 186 |
+
compliance_result TEXT,
|
| 187 |
+
next_due_note TEXT,
|
| 188 |
+
created_at TEXT
|
| 189 |
+
)
|
| 190 |
+
"""
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
conn.commit()
|
| 194 |
+
conn.close()
|
| 195 |
+
|
| 196 |
+
def load_clients():
|
| 197 |
+
conn = get_conn()
|
| 198 |
+
try:
|
| 199 |
+
df = pd.read_sql_query(
|
| 200 |
+
"""
|
| 201 |
+
SELECT id, name, masked_name, gender, birth_year, care_grade,
|
| 202 |
+
recognition_number, recognition_start_date, recognition_end_date,
|
| 203 |
+
institution_type, institution_name, admission_date,
|
| 204 |
+
main_condition, cognitive_status, mobility_status,
|
| 205 |
+
diet_status, toileting_status, guardian_name, guardian_phone,
|
| 206 |
+
notes, status
|
| 207 |
+
FROM clients
|
| 208 |
+
ORDER BY id DESC
|
| 209 |
+
""",
|
| 210 |
+
conn,
|
| 211 |
+
)
|
| 212 |
+
except Exception:
|
| 213 |
+
df = pd.DataFrame()
|
| 214 |
+
conn.close()
|
| 215 |
+
return df
|
| 216 |
+
|
| 217 |
+
def save_counseling_record(data):
|
| 218 |
+
conn = get_conn()
|
| 219 |
+
cur = conn.cursor()
|
| 220 |
+
cur.execute(
|
| 221 |
+
"""
|
| 222 |
+
INSERT INTO counseling_records (
|
| 223 |
+
client_id, client_masked_name, institution_type, counseling_type,
|
| 224 |
+
counseling_date, counselor, counseling_reason, client_status_change,
|
| 225 |
+
guardian_opinion, counseling_content, action_plan, evaluation_score,
|
| 226 |
+
missing_items, compliance_result, next_due_note, created_at
|
| 227 |
+
)
|
| 228 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 229 |
+
""",
|
| 230 |
+
(
|
| 231 |
+
data["client_id"],
|
| 232 |
+
data["client_masked_name"],
|
| 233 |
+
data["institution_type"],
|
| 234 |
+
data["counseling_type"],
|
| 235 |
+
data["counseling_date"],
|
| 236 |
+
data["counselor"],
|
| 237 |
+
data["counseling_reason"],
|
| 238 |
+
data["client_status_change"],
|
| 239 |
+
data["guardian_opinion"],
|
| 240 |
+
data["counseling_content"],
|
| 241 |
+
data["action_plan"],
|
| 242 |
+
data["evaluation_score"],
|
| 243 |
+
data["missing_items"],
|
| 244 |
+
data["compliance_result"],
|
| 245 |
+
data["next_due_note"],
|
| 246 |
+
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 247 |
+
),
|
| 248 |
+
)
|
| 249 |
+
conn.commit()
|
| 250 |
+
conn.close()
|
| 251 |
+
|
| 252 |
+
def load_records():
|
| 253 |
+
conn = get_conn()
|
| 254 |
+
try:
|
| 255 |
+
df = pd.read_sql_query("SELECT * FROM counseling_records ORDER BY id DESC", conn)
|
| 256 |
+
except Exception:
|
| 257 |
+
df = pd.DataFrame()
|
| 258 |
+
conn.close()
|
| 259 |
+
return df
|
| 260 |
+
|
| 261 |
+
def safe(row, key, default=""):
|
| 262 |
+
try:
|
| 263 |
+
value = row.get(key, default)
|
| 264 |
+
if pd.isna(value):
|
| 265 |
+
return default
|
| 266 |
+
return str(value)
|
| 267 |
+
except Exception:
|
| 268 |
+
return default
|
| 269 |
+
|
| 270 |
+
def mask_name(name):
|
| 271 |
+
if not name:
|
| 272 |
+
return ""
|
| 273 |
+
name = str(name).strip()
|
| 274 |
+
if len(name) >= 3:
|
| 275 |
+
return name[0] + "○" + name[2:]
|
| 276 |
+
if len(name) == 2:
|
| 277 |
+
return name[0] + "○"
|
| 278 |
+
return name
|
| 279 |
+
|
| 280 |
+
def recognition_summary(row):
|
| 281 |
+
no = safe(row, "recognition_number")
|
| 282 |
+
start = safe(row, "recognition_start_date")
|
| 283 |
+
end = safe(row, "recognition_end_date")
|
| 284 |
+
return no, start, end
|
| 285 |
+
|
| 286 |
+
def days_until(end_date_text, base_date):
|
| 287 |
+
d = parse_date(end_date_text)
|
| 288 |
+
if not d:
|
| 289 |
+
return "인정기간 종료일 미입력"
|
| 290 |
+
diff = (d - base_date).days
|
| 291 |
+
if diff < 0:
|
| 292 |
+
return f"인정기간 만료 {abs(diff)}일 경과"
|
| 293 |
+
return f"인정기간 만료까지 {diff}일 남음"
|
| 294 |
+
|
| 295 |
+
init_db()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# -----------------------------
|
| 299 |
+
# 상담 문장 생성 로직
|
| 300 |
+
# -----------------------------
|
| 301 |
+
VARIATION_OPENERS = [
|
| 302 |
+
"상담 과정에서 확인한 결과",
|
| 303 |
+
"금일 상담을 통해 파악한 내용은",
|
| 304 |
+
"최근 서비스 제공 상황을 종합해 보면",
|
| 305 |
+
"수급자 및 관련자의 의견을 확인한 결과",
|
| 306 |
+
"상태 변화와 서비스 이용 상황을 함께 살펴본 결과",
|
| 307 |
+
]
|
| 308 |
+
|
| 309 |
+
VARIATION_TONES = [
|
| 310 |
+
"현재 상태를 유지하면서도 세심한 관찰이 요구됩니다.",
|
| 311 |
+
"일상생활의 안정성을 높이기 위한 지속적인 지원이 필요합니다.",
|
| 312 |
+
"서비스 제공 과정에서 개별 욕구가 충분히 반영되도록 조정이 필요합니다.",
|
| 313 |
+
"상태 변화 가능성을 고려하여 정기적인 확인과 기록이 필요합니다.",
|
| 314 |
+
"보호자와의 정보 공유를 통해 급여제공 방향을 보완할 필요가 있습니다.",
|
| 315 |
+
]
|
| 316 |
+
|
| 317 |
+
TYPE_GUIDES = {
|
| 318 |
+
"수급자상담": {
|
| 319 |
+
"focus": "수급자의 건강상태, 정서상태, 일상생활 불편감, 서비스 만족도, 상태변화를 중심으로 상담",
|
| 320 |
+
"action": "수급자 욕구를 급여제공계획과 일일 서비스 제공 내용에 반영",
|
| 321 |
+
},
|
| 322 |
+
"보호자상담": {
|
| 323 |
+
"focus": "보호자의 의견, 가족 요청사항, 상태변화 전달, 서비스 조정 필요성을 중심으로 상담",
|
| 324 |
+
"action": "보호자 의견을 기록하고 필요한 경우 급여제공계획 변경 또는 직원 공유",
|
| 325 |
+
},
|
| 326 |
+
"종사자상담": {
|
| 327 |
+
"focus": "서비스 제공 중 관찰사항, 업무 고충, 수급자 상태 변화, 안전관리 필요성을 중심으로 상담",
|
| 328 |
+
"action": "종사자 관찰 내용을 반영하여 서비스 방법을 조정하고 필요 시 교육·회의 안건으로 연결",
|
| 329 |
+
},
|
| 330 |
+
"기타상담": {
|
| 331 |
+
"focus": "기관 운영상 필요한 상담, 지역자원 연계, 민원 예방, 특이사항 확인을 중심으로 상담",
|
| 332 |
+
"action": "상담 내용을 기관 기록으로 남기고 후속조치 담당자와 기한을 설정",
|
| 333 |
+
},
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
INSTITUTION_GUIDES = {
|
| 337 |
+
"방문요양": ["서비스 시간", "요양보호사 변경", "가사지원 범위", "인지활동", "복약확인", "낙상예방"],
|
| 338 |
+
"방문목욕": ["목욕 전후 건강상태", "피부상태", "낙상예방", "이동 보조", "목욕 거부감", "보호자 협조"],
|
| 339 |
+
"방문간호": ["혈압/혈당 관찰", "상처관리", "투약관리", "건강상담", "의료기관 연계", "간호처치"],
|
| 340 |
+
"주간보호": ["송영", "프로그램 참여", "식사", "배변", "낙상예방", "정서지원", "가족소통"],
|
| 341 |
+
"요양원": ["입소생활 적응", "식사/수면/배변", "욕창예방", "낙상예방", "프로그램 참여", "가족면회"],
|
| 342 |
+
"공동생활가정": ["공동생활 적응", "정서지원", "개별 욕구", "가족소통", "프로그램 참여", "안전관리"],
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
def build_counseling_text(client, institution_type, counseling_type, reason, status_change, guardian_opinion, staff_observation, custom_need):
|
| 346 |
+
opener = random.choice(VARIATION_OPENERS)
|
| 347 |
+
tone = random.choice(VARIATION_TONES)
|
| 348 |
+
guide = TYPE_GUIDES[counseling_type]
|
| 349 |
+
inst_keywords = ", ".join(INSTITUTION_GUIDES.get(institution_type, []))
|
| 350 |
+
|
| 351 |
+
masked_name = safe(client, "masked_name", "수급자")
|
| 352 |
+
grade = safe(client, "care_grade")
|
| 353 |
+
main_condition = safe(client, "main_condition")
|
| 354 |
+
cognitive = safe(client, "cognitive_status")
|
| 355 |
+
mobility = safe(client, "mobility_status")
|
| 356 |
+
diet = safe(client, "diet_status")
|
| 357 |
+
toileting = safe(client, "toileting_status")
|
| 358 |
+
|
| 359 |
+
status_part = status_change if status_change.strip() else "특이한 급격한 변화는 확인되지 않았으나 지속적인 관찰이 필요함"
|
| 360 |
+
guardian_part = guardian_opinion if guardian_opinion.strip() else "보호자 의견은 추가 확인이 필요하며, 필요 시 유선상담을 통해 반영 예정"
|
| 361 |
+
staff_part = staff_observation if staff_observation.strip() else "서비스 제공 중 관찰된 내용을 종합하여 급여 방향을 점검함"
|
| 362 |
+
need_part = custom_need if custom_need.strip() else "현재 제공 중인 서비스가 수급자의 욕구와 상태에 적절히 맞는지 점검함"
|
| 363 |
+
|
| 364 |
+
content = f"""
|
| 365 |
+
{opener}, {masked_name} 수급자는 {grade} 대상자로서 {institution_type} 서비스 이용 과정에서 {reason} 관련 상담이 필요하다고 판단되었습니다.
|
| 366 |
+
|
| 367 |
+
현재 주요 상태는 {main_condition or '기존 질환 및 기능상태에 대한 지속 관찰 필요'}이며, 인지상태는 {cognitive or '정기 관찰 필요'}, 이동상태는 {mobility or '안전한 이동 지원 필요'}로 확인됩니다. 식사상태는 {diet or '개별 식사상태 확인 필요'}, 배변·배뇨상태는 {toileting or '배변·배뇨 양상 관찰 필요'}로 기록됩니다.
|
| 368 |
+
|
| 369 |
+
이번 상담에서는 {guide['focus']}하였으며, 기관유형상 특히 {inst_keywords} 항목을 중심으로 확인하였습니다. 상태변화와 관련해서는 {status_part}으로 정리됩니다.
|
| 370 |
+
|
| 371 |
+
보호자 의견은 "{guardian_part}"으로 확인되었고, 종사자 관찰 내용은 "{staff_part}"입니다. 추가 욕구 또는 요청사항은 "{need_part}"로 정리하여 향후 급여제공 과정에 반영합니다.
|
| 372 |
+
|
| 373 |
+
종합적으로 {tone} 상담 결과는 단순 기록에 그치지 않고 {guide['action']}하는 방향으로 관리하겠습니다.
|
| 374 |
+
""".strip()
|
| 375 |
+
|
| 376 |
+
action = f"""
|
| 377 |
+
1. 상담 내용을 급여제공 담당자와 공유합니다.
|
| 378 |
+
2. 상태변화가 확인된 항목은 다음 서비스 제공 시 관찰기록에 반영합니다.
|
| 379 |
+
3. 보호자 의견이 있는 경우 유선 또는 대면상담 기록으로 추가 확인합니다.
|
| 380 |
+
4. {institution_type} 특성에 맞추어 {inst_keywords} 관련 서비스를 점검합니다.
|
| 381 |
+
5. 필요 시 욕구사정, 급여제공계획서, 사례관리 회의 안건으로 연계합니다.
|
| 382 |
+
""".strip()
|
| 383 |
+
|
| 384 |
+
return content, action
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# -----------------------------
|
| 388 |
+
# 평가 적합도 점검
|
| 389 |
+
# -----------------------------
|
| 390 |
+
def evaluate_record(counseling_type, reason, status_change, guardian_opinion, staff_observation, counseling_content, action_plan):
|
| 391 |
+
required = {
|
| 392 |
+
"상담일자": True,
|
| 393 |
+
"상담대상/분류": bool(counseling_type),
|
| 394 |
+
"상담사유": bool(reason.strip()),
|
| 395 |
+
"상태변화 반영": bool(status_change.strip()) or "상태변화" in counseling_content or "관찰" in counseling_content,
|
| 396 |
+
"보호자 의견 반영": bool(guardian_opinion.strip()) or counseling_type == "보호자상담" or "보호자" in counseling_content,
|
| 397 |
+
"종사자 관찰 반영": bool(staff_observation.strip()) or counseling_type == "종사자상담" or "종사자" in counseling_content,
|
| 398 |
+
"후속조치": bool(action_plan.strip()),
|
| 399 |
+
"급여제공 반영": "급여" in counseling_content or "서비스" in counseling_content or "계획" in action_plan,
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
score = int(sum(required.values()) / len(required) * 100)
|
| 403 |
+
missing = [k for k, v in required.items() if not v]
|
| 404 |
+
|
| 405 |
+
if score >= 90:
|
| 406 |
+
result = "평가 적합도가 높습니다. 상담사유, 상태변화, 후속조치가 비교적 잘 반영되었습니다."
|
| 407 |
+
elif score >= 75:
|
| 408 |
+
result = "대체로 적합하나 일부 보완이 필요합니다. 부족 항목을 추가하면 평가 대응력이 높아집니다."
|
| 409 |
+
else:
|
| 410 |
+
result = "보완이 필요합니다. 상담사유, 상태변화, 보호자 의견, 후속조치가 구체적으로 들어가야 합니다."
|
| 411 |
+
|
| 412 |
+
return score, missing, result
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
# -----------------------------
|
| 416 |
+
# 기한 알림
|
| 417 |
+
# -----------------------------
|
| 418 |
+
def parse_date(text):
|
| 419 |
+
if not text:
|
| 420 |
+
return None
|
| 421 |
+
try:
|
| 422 |
+
return pd.to_datetime(text).date()
|
| 423 |
+
except Exception:
|
| 424 |
+
return None
|
| 425 |
+
|
| 426 |
+
def due_alerts(admission_date_text, base_date, recognition_end_text=""):
|
| 427 |
+
alerts = []
|
| 428 |
+
rec_end = parse_date(recognition_end_text)
|
| 429 |
+
if rec_end:
|
| 430 |
+
remain_rec = (rec_end - base_date).days
|
| 431 |
+
if remain_rec < 0:
|
| 432 |
+
alerts.append(f"인정기간: {abs(remain_rec)}일 경과 → 갱신 여부 확인 필요")
|
| 433 |
+
elif remain_rec <= 90:
|
| 434 |
+
alerts.append(f"인정기간: {remain_rec}일 남음 → 급여제공계획 재점검 및 갱신 준비 권장")
|
| 435 |
+
else:
|
| 436 |
+
alerts.append(f"인정기간: {remain_rec}일 남음")
|
| 437 |
+
else:
|
| 438 |
+
alerts.append("인정기간 종료일 미입력 → 인정기간 기준 알림은 표시되지 않습니다.")
|
| 439 |
+
|
| 440 |
+
adm = parse_date(admission_date_text)
|
| 441 |
+
if not adm:
|
| 442 |
+
alerts.append("이용 시작일/입소일이 없어 욕구사정·계획서 기한 계산이 어렵습니다.")
|
| 443 |
+
return alerts
|
| 444 |
+
|
| 445 |
+
checks = [
|
| 446 |
+
("초기 욕구사정", adm + timedelta(days=30)),
|
| 447 |
+
("급여제공계획서 점검", adm + timedelta(days=30)),
|
| 448 |
+
("30일 후 결과평가", adm + timedelta(days=30)),
|
| 449 |
+
("정기 상담 점검", adm + timedelta(days=90)),
|
| 450 |
+
("욕구사정 재점검", adm + timedelta(days=180)),
|
| 451 |
+
]
|
| 452 |
+
|
| 453 |
+
for title, due in checks:
|
| 454 |
+
remain = (due - base_date).days
|
| 455 |
+
if remain < 0:
|
| 456 |
+
alerts.append(f"{title}: {abs(remain)}일 경과 → 상담기록에 지연 사유와 후속조치 반영 권장")
|
| 457 |
+
elif remain <= 14:
|
| 458 |
+
alerts.append(f"{title}: {remain}일 남음 → 상담기록에 점검 예정 내용 반영 권장")
|
| 459 |
+
else:
|
| 460 |
+
alerts.append(f"{title}: {remain}일 남음")
|
| 461 |
+
|
| 462 |
+
return alerts
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# -----------------------------
|
| 466 |
+
# 엑셀 출력 (디자인 및 정렬 최적화)
|
| 467 |
+
# -----------------------------
|
| 468 |
+
def style_range(ws, cell_range, border_on=True, fill=None, font=None, alignment=None):
|
| 469 |
+
"""병합 셀 포함 범위 전체에 스타일 적용 (검정색 얇은 테두리로 가시성 확보)"""
|
| 470 |
+
thin = Side(style="thin", color="000000")
|
| 471 |
+
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 472 |
+
|
| 473 |
+
cells = ws[cell_range]
|
| 474 |
+
if not isinstance(cells, tuple):
|
| 475 |
+
cells = ((cells,),)
|
| 476 |
+
|
| 477 |
+
for row in cells:
|
| 478 |
+
for cell in row:
|
| 479 |
+
if border_on:
|
| 480 |
+
cell.border = border
|
| 481 |
+
if fill:
|
| 482 |
+
cell.fill = fill
|
| 483 |
+
if font:
|
| 484 |
+
cell.font = font
|
| 485 |
+
if alignment:
|
| 486 |
+
cell.alignment = alignment
|
| 487 |
+
|
| 488 |
+
def generate_excel(data):
|
| 489 |
+
wb = Workbook()
|
| 490 |
+
ws = wb.active
|
| 491 |
+
ws.title = "상담일지"
|
| 492 |
+
|
| 493 |
+
# A4 비율 맞춤 설정 (선 잘림 방지)
|
| 494 |
+
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
| 495 |
+
ws.page_setup.orientation = "portrait"
|
| 496 |
+
ws.page_setup.fitToWidth = 1
|
| 497 |
+
ws.page_setup.fitToHeight = 0
|
| 498 |
+
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
| 499 |
+
ws.page_margins.left = 0.3
|
| 500 |
+
ws.page_margins.right = 0.3
|
| 501 |
+
ws.page_margins.top = 0.4
|
| 502 |
+
ws.page_margins.bottom = 0.4
|
| 503 |
+
ws.sheet_view.showGridLines = False
|
| 504 |
+
|
| 505 |
+
title_fill = PatternFill("solid", fgColor="E2F0D9")
|
| 506 |
+
header_fill = PatternFill("solid", fgColor="F2F2F2")
|
| 507 |
+
|
| 508 |
+
# 전체 열 너비 조정
|
| 509 |
+
for col in range(1, 10):
|
| 510 |
+
ws.column_dimensions[get_column_letter(col)].width = 11.5
|
| 511 |
+
|
| 512 |
+
# 1. 상단 결재라인 및 큰 제목 세팅 (A1~G2 병합 제목 / H1~I2 결재라인)
|
| 513 |
+
ws.merge_cells("A1:G2")
|
| 514 |
+
title_cell = ws.cell(1, 1)
|
| 515 |
+
title_cell.value = "상 담 일 지"
|
| 516 |
+
title_cell.font = Font(name="Malgun Gothic", size=24, bold=True)
|
| 517 |
+
title_cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 518 |
+
style_range(ws, "A1:G2", fill=title_fill)
|
| 519 |
+
|
| 520 |
+
# 결재라인: H, I열 (우측 상단 2칸 지정 및 지저분한 테두리 제거)
|
| 521 |
+
ws.cell(1, 8).value = "담당자"
|
| 522 |
+
ws.cell(1, 9).value = "시설장"
|
| 523 |
+
ws.cell(2, 8).value = ""
|
| 524 |
+
ws.cell(2, 9).value = ""
|
| 525 |
+
|
| 526 |
+
for r in [1, 2]:
|
| 527 |
+
for c_idx in [8, 9]:
|
| 528 |
+
cell = ws.cell(r, c_idx)
|
| 529 |
+
cell.alignment = Alignment(horizontal="center", vertical="center")
|
| 530 |
+
if r == 1:
|
| 531 |
+
cell.font = Font(name="Malgun Gothic", size=11, bold=True)
|
| 532 |
+
cell.fill = header_fill
|
| 533 |
+
else:
|
| 534 |
+
cell.font = Font(name="Malgun Gothic", size=11)
|
| 535 |
+
|
| 536 |
+
# 셀 단위별로만 테두리를 씌워서 지저분한 칸이 없도록 설정
|
| 537 |
+
cell_name = f"{get_column_letter(c_idx)}{r}"
|
| 538 |
+
style_range(ws, f"{cell_name}:{cell_name}")
|
| 539 |
+
|
| 540 |
+
ws.row_dimensions[1].height = 28
|
| 541 |
+
ws.row_dimensions[2].height = 45
|
| 542 |
+
|
| 543 |
+
# 2. 기본 정보 영역 렌더링 함수
|
| 544 |
+
def write_info_row(row, a, b, c_val, d, e, f):
|
| 545 |
+
ws.cell(row, 1).value = a
|
| 546 |
+
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=3)
|
| 547 |
+
ws.cell(row, 2).value = b
|
| 548 |
+
ws.cell(row, 4).value = c_val
|
| 549 |
+
ws.merge_cells(start_row=row, start_column=5, end_row=row, end_column=6)
|
| 550 |
+
ws.cell(row, 5).value = d
|
| 551 |
+
ws.cell(row, 7).value = e
|
| 552 |
+
ws.merge_cells(start_row=row, start_column=8, end_row=row, end_column=9)
|
| 553 |
+
ws.cell(row, 8).value = f
|
| 554 |
+
|
| 555 |
+
for col in [1, 4, 7]:
|
| 556 |
+
cell = ws.cell(row, col)
|
| 557 |
+
cell.fill = header_fill
|
| 558 |
+
cell.font = Font(name="Malgun Gothic", size=11, bold=True)
|
| 559 |
+
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 560 |
+
for col in [2, 5, 8]:
|
| 561 |
+
cell = ws.cell(row, col)
|
| 562 |
+
cell.font = Font(name="Malgun Gothic", size=11)
|
| 563 |
+
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 564 |
+
|
| 565 |
+
style_range(ws, f"A{row}:I{row}")
|
| 566 |
+
ws.row_dimensions[row].height = 30
|
| 567 |
+
|
| 568 |
+
r = 3
|
| 569 |
+
write_info_row(r, "수급자", data["client_masked_name"], "기관유형", data["institution_type"], "상담분류", data["counseling_type"]); r += 1
|
| 570 |
+
write_info_row(r, "인정번호", data.get("recognition_number", ""), "인정시작", data.get("recognition_start_date", ""), "인정종료", data.get("recognition_end_date", "")); r += 1
|
| 571 |
+
write_info_row(r, "상담일자", data["counseling_date"], "상담자", data["counselor"], "평가적합도", f"{data['evaluation_score']}점"); r += 1
|
| 572 |
+
write_info_row(r, "상담사유", data["counseling_reason"], "상태변화", data["client_status_change"], "보호자 의견", data["guardian_opinion"]); r += 1
|
| 573 |
+
|
| 574 |
+
# 3. 상세 기록 영역
|
| 575 |
+
detail_rows = [
|
| 576 |
+
("상담내용", data["counseling_content"], 120),
|
| 577 |
+
("조치계획", data["action_plan"], 90),
|
| 578 |
+
("평가 적합도\n점검결과", data["compliance_result"], 60),
|
| 579 |
+
("부족한 항목", data["missing_items"], 45),
|
| 580 |
+
("기한 알림", data["next_due_note"], 60),
|
| 581 |
+
]
|
| 582 |
+
|
| 583 |
+
for label, content_val, min_h in detail_rows:
|
| 584 |
+
# 타이틀 셀 설정
|
| 585 |
+
title_cell = ws.cell(r, 1)
|
| 586 |
+
title_cell.value = label
|
| 587 |
+
title_cell.font = Font(name="Malgun Gothic", size=11, bold=True)
|
| 588 |
+
title_cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 589 |
+
title_cell.fill = header_fill
|
| 590 |
+
|
| 591 |
+
# 내용 영역 병합 및 설정
|
| 592 |
+
ws.merge_cells(start_row=r, start_column=2, end_row=r, end_column=9)
|
| 593 |
+
content_cell = ws.cell(r, 2)
|
| 594 |
+
content_cell.value = content_val
|
| 595 |
+
content_cell.font = Font(name="Malgun Gothic", size=11)
|
| 596 |
+
|
| 597 |
+
# 안내 문구가 들어간 항목은 중앙정렬, 실제 작성 내용은 상단/좌측 정렬
|
| 598 |
+
valign = "center" if "점검결과" in label or "항목" in label else "top"
|
| 599 |
+
content_cell.alignment = Alignment(horizontal="left", vertical=valign, wrap_text=True)
|
| 600 |
+
|
| 601 |
+
# 텍스트 잘림을 완전히 막기 위한 행 높이 여유 계산값 추가
|
| 602 |
+
lines = 0
|
| 603 |
+
for line in str(content_val).split("\n"):
|
| 604 |
+
lines += (len(line) // 35) + 1 # 글자수에 비례해 줄바꿈 더 넉넉히 적용
|
| 605 |
+
calculated_height = lines * 24 + 30 # 가독성 및 여유공간 확대
|
| 606 |
+
|
| 607 |
+
ws.row_dimensions[r].height = max(min_h, calculated_height)
|
| 608 |
+
style_range(ws, f"A{r}:I{r}")
|
| 609 |
+
r += 1
|
| 610 |
+
|
| 611 |
+
buffer = BytesIO()
|
| 612 |
+
wb.save(buffer)
|
| 613 |
+
buffer.seek(0)
|
| 614 |
+
return buffer
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
# -----------------------------
|
| 618 |
+
# 화면 메뉴
|
| 619 |
+
# -----------------------------
|
| 620 |
+
menu = st.sidebar.radio(
|
| 621 |
+
"메뉴",
|
| 622 |
+
["상담일지 생성", "상담기록 보기", "기한 알림"],
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
st.sidebar.success("DB 연결")
|
| 626 |
+
st.sidebar.caption(DB_PATH)
|
| 627 |
+
|
| 628 |
+
clients_df = load_clients()
|
| 629 |
+
|
| 630 |
+
if menu == "상담일지 생성":
|
| 631 |
+
st.subheader("1단계. 기관유형 선택")
|
| 632 |
+
|
| 633 |
+
inst_cols = st.columns(6)
|
| 634 |
+
inst_list = ["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"]
|
| 635 |
+
|
| 636 |
+
if "selected_inst" not in st.session_state:
|
| 637 |
+
st.session_state["selected_inst"] = "방문요양"
|
| 638 |
+
|
| 639 |
+
for i, inst in enumerate(inst_list):
|
| 640 |
+
if inst_cols[i].button(inst, use_container_width=True):
|
| 641 |
+
st.session_state["selected_inst"] = inst
|
| 642 |
+
|
| 643 |
+
institution_type = st.session_state["selected_inst"]
|
| 644 |
+
st.markdown(f"### 선택된 기관유형: **{institution_type}**")
|
| 645 |
+
|
| 646 |
+
st.subheader("2단계. 수급자 선택")
|
| 647 |
+
|
| 648 |
+
selected_client = None
|
| 649 |
+
if clients_df.empty:
|
| 650 |
+
st.warning("Client Center에 등록된 수급자가 없습니다. 아래 직접 입력값으로 임시 생성할 수 있습니다.")
|
| 651 |
+
temp_name = st.text_input("수급자 이름", "홍길동")
|
| 652 |
+
selected_client = pd.Series({
|
| 653 |
+
"id": 0,
|
| 654 |
+
"name": temp_name,
|
| 655 |
+
"masked_name": mask_name(temp_name),
|
| 656 |
+
"gender": "",
|
| 657 |
+
"birth_year": "",
|
| 658 |
+
"care_grade": "",
|
| 659 |
+
"recognition_number": "",
|
| 660 |
+
"recognition_start_date": "",
|
| 661 |
+
"recognition_end_date": "",
|
| 662 |
+
"institution_type": institution_type,
|
| 663 |
+
"institution_name": "",
|
| 664 |
+
"admission_date": "",
|
| 665 |
+
"main_condition": "",
|
| 666 |
+
"cognitive_status": "",
|
| 667 |
+
"mobility_status": "",
|
| 668 |
+
"diet_status": "",
|
| 669 |
+
"toileting_status": "",
|
| 670 |
+
"guardian_name": "",
|
| 671 |
+
"guardian_phone": "",
|
| 672 |
+
"notes": "",
|
| 673 |
+
"status": "",
|
| 674 |
+
})
|
| 675 |
+
else:
|
| 676 |
+
filtered_df = clients_df[
|
| 677 |
+
(clients_df["institution_type"] == institution_type) |
|
| 678 |
+
(clients_df["institution_type"].isna()) |
|
| 679 |
+
(clients_df["institution_type"] == "")
|
| 680 |
+
]
|
| 681 |
+
|
| 682 |
+
if filtered_df.empty:
|
| 683 |
+
filtered_df = clients_df
|
| 684 |
+
|
| 685 |
+
options = filtered_df.apply(
|
| 686 |
+
lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_type']} / {x['status']}",
|
| 687 |
+
axis=1,
|
| 688 |
+
).tolist()
|
| 689 |
+
|
| 690 |
+
selected_option = st.selectbox("수급자 선택", options)
|
| 691 |
+
selected_id = int(selected_option.split("번")[0])
|
| 692 |
+
selected_client = filtered_df[filtered_df["id"] == selected_id].iloc[0]
|
| 693 |
+
|
| 694 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 695 |
+
c1.metric("수급자", safe(selected_client, "masked_name"))
|
| 696 |
+
c2.metric("등급", safe(selected_client, "care_grade"))
|
| 697 |
+
c3.metric("기관유형", institution_type)
|
| 698 |
+
c4.metric("상태", safe(selected_client, "status"))
|
| 699 |
+
|
| 700 |
+
rec_no, rec_start, rec_end = recognition_summary(selected_client)
|
| 701 |
+
r1, r2, r3 = st.columns(3)
|
| 702 |
+
r1.metric("인정번호", rec_no or "미입력")
|
| 703 |
+
r2.metric("인정기간", f"{rec_start or '-'} ~ {rec_end or '-'}")
|
| 704 |
+
r3.metric("인정기간 알림", days_until(rec_end, date.today()))
|
| 705 |
+
|
| 706 |
+
st.subheader("3단계. 상담분류 선택")
|
| 707 |
+
counseling_type = st.radio(
|
| 708 |
+
"상담분류",
|
| 709 |
+
["수급자상담", "보호자상담", "종사자상담", "기타상담"],
|
| 710 |
+
horizontal=True,
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
st.subheader("4단계. 상담 내용 입력")
|
| 714 |
+
|
| 715 |
+
today = date.today()
|
| 716 |
+
col_a, col_b, col_c = st.columns(3)
|
| 717 |
+
counseling_date = col_a.date_input("상담일자", value=today)
|
| 718 |
+
counselor = col_b.text_input("상담자", "사회복지사")
|
| 719 |
+
counseling_reason = col_c.selectbox(
|
| 720 |
+
"상담사유",
|
| 721 |
+
[
|
| 722 |
+
"정기상담",
|
| 723 |
+
"신규 이용 후 초기상담",
|
| 724 |
+
"상태변화 확인",
|
| 725 |
+
"보호자 요청",
|
| 726 |
+
"서비스 변경 요청",
|
| 727 |
+
"직원 관찰사항",
|
| 728 |
+
"낙상/욕창/건강위험",
|
| 729 |
+
"프로그램 참여 변화",
|
| 730 |
+
"퇴소/전원/입원 관련",
|
| 731 |
+
"기타",
|
| 732 |
+
],
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
col_d, col_e = st.columns(2)
|
| 736 |
+
client_status_change = col_d.text_area(
|
| 737 |
+
"수급자 상태변화",
|
| 738 |
+
placeholder="예: 최근 보행 시 휘청거림 증가, 식사량 감소, 수면 변화, 정서 변화 등",
|
| 739 |
+
height=100,
|
| 740 |
+
)
|
| 741 |
+
guardian_opinion = col_e.text_area(
|
| 742 |
+
"보호자 의견",
|
| 743 |
+
placeholder="예: 보호자가 식사량 감소를 걱정함, 서비스 시간 조정을 요청함 등",
|
| 744 |
+
height=100,
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
col_f, col_g = st.columns(2)
|
| 748 |
+
staff_observation = col_f.text_area(
|
| 749 |
+
"종사자 관찰사항",
|
| 750 |
+
placeholder="예: 요양보호사가 목욕 시 피부 발적을 관찰함, 주간보호 프로그램 참여도가 낮아짐 등",
|
| 751 |
+
height=100,
|
| 752 |
+
)
|
| 753 |
+
custom_need = col_g.text_area(
|
| 754 |
+
"추가 욕구 / 요청사항",
|
| 755 |
+
placeholder="예: 인지활동 확대, 병원동행 상담, 가족상담 필요 등",
|
| 756 |
+
height=100,
|
| 757 |
+
)
|
| 758 |
+
|
| 759 |
+
alerts = due_alerts(safe(selected_client, "admission_date"), counseling_date, safe(selected_client, "recognition_end_date"))
|
| 760 |
+
due_note = "\n".join(alerts)
|
| 761 |
+
|
| 762 |
+
with st.expander("⏰ 욕구사정·계획서·결과평가 기한 알림 보기", expanded=True):
|
| 763 |
+
for a in alerts:
|
| 764 |
+
if "경과" in a or "남음 →" in a:
|
| 765 |
+
st.warning(a)
|
| 766 |
+
else:
|
| 767 |
+
st.info(a)
|
| 768 |
+
|
| 769 |
+
if st.button("📝 상담일지 생성", use_container_width=True):
|
| 770 |
+
content, action_plan = build_counseling_text(
|
| 771 |
+
selected_client,
|
| 772 |
+
institution_type,
|
| 773 |
+
counseling_type,
|
| 774 |
+
counseling_reason,
|
| 775 |
+
client_status_change,
|
| 776 |
+
guardian_opinion,
|
| 777 |
+
staff_observation,
|
| 778 |
+
custom_need,
|
| 779 |
+
)
|
| 780 |
+
score, missing, result = evaluate_record(
|
| 781 |
+
counseling_type,
|
| 782 |
+
counseling_reason,
|
| 783 |
+
client_status_change,
|
| 784 |
+
guardian_opinion,
|
| 785 |
+
staff_observation,
|
| 786 |
+
content,
|
| 787 |
+
action_plan,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
st.session_state["counseling_data"] = {
|
| 791 |
+
"client_id": int(safe(selected_client, "id", 0) or 0),
|
| 792 |
+
"client_masked_name": safe(selected_client, "masked_name"),
|
| 793 |
+
"institution_type": institution_type,
|
| 794 |
+
"recognition_number": safe(selected_client, "recognition_number"),
|
| 795 |
+
"recognition_start_date": safe(selected_client, "recognition_start_date"),
|
| 796 |
+
"recognition_end_date": safe(selected_client, "recognition_end_date"),
|
| 797 |
+
"counseling_type": counseling_type,
|
| 798 |
+
"counseling_date": str(counseling_date),
|
| 799 |
+
"counselor": counselor,
|
| 800 |
+
"counseling_reason": counseling_reason,
|
| 801 |
+
"client_status_change": client_status_change,
|
| 802 |
+
"guardian_opinion": guardian_opinion,
|
| 803 |
+
"counseling_content": content,
|
| 804 |
+
"action_plan": action_plan,
|
| 805 |
+
"evaluation_score": score,
|
| 806 |
+
"missing_items": ", ".join(missing) if missing else "부족 항목 없음",
|
| 807 |
+
"compliance_result": result,
|
| 808 |
+
"next_due_note": due_note,
|
| 809 |
+
}
|
| 810 |
+
|
| 811 |
+
if "counseling_data" in st.session_state:
|
| 812 |
+
data = st.session_state["counseling_data"]
|
| 813 |
+
|
| 814 |
+
st.markdown("---")
|
| 815 |
+
st.subheader("생성된 상담일지")
|
| 816 |
+
|
| 817 |
+
edited_content = st.text_area("상담내용", value=data["counseling_content"], height=240)
|
| 818 |
+
edited_action = st.text_area("조치계획", value=data["action_plan"], height=140)
|
| 819 |
+
|
| 820 |
+
data["counseling_content"] = edited_content
|
| 821 |
+
data["action_plan"] = edited_action
|
| 822 |
+
|
| 823 |
+
score, missing, result = evaluate_record(
|
| 824 |
+
data["counseling_type"],
|
| 825 |
+
data["counseling_reason"],
|
| 826 |
+
data["client_status_change"],
|
| 827 |
+
data["guardian_opinion"],
|
| 828 |
+
staff_observation,
|
| 829 |
+
edited_content,
|
| 830 |
+
edited_action,
|
| 831 |
+
)
|
| 832 |
+
|
| 833 |
+
data["evaluation_score"] = score
|
| 834 |
+
data["missing_items"] = ", ".join(missing) if missing else "부족 항목 없음"
|
| 835 |
+
data["compliance_result"] = result
|
| 836 |
+
|
| 837 |
+
st.subheader("평가 적합도 점검")
|
| 838 |
+
m1, m2, m3 = st.columns(3)
|
| 839 |
+
m1.metric("평가 적합도", f"{score}점")
|
| 840 |
+
m2.metric("부족 항목", data["missing_items"])
|
| 841 |
+
m3.metric("보호자 의견 반영", "반영" if "보호자 의견 반영" not in missing else "보완 필요")
|
| 842 |
+
|
| 843 |
+
if score >= 90:
|
| 844 |
+
st.markdown(f'<div class="okbox">{result}</div>', unsafe_allow_html=True)
|
| 845 |
+
else:
|
| 846 |
+
st.markdown(f'<div class="warnbox">{result}</div>', unsafe_allow_html=True)
|
| 847 |
+
|
| 848 |
+
if st.button("💾 상담기록 DB에 저장", use_container_width=True):
|
| 849 |
+
save_counseling_record(data)
|
| 850 |
+
st.success("상담기록에 저장되었습니다.")
|
| 851 |
+
|
| 852 |
+
file_name = f"상담일지_{data['client_masked_name']}_{data['counseling_type']}_{datetime.now().strftime('%Y%m%d')}.xlsx"
|
| 853 |
+
st.download_button(
|
| 854 |
+
"📥 상담일지 엑셀 다운로드",
|
| 855 |
+
data=generate_excel(data),
|
| 856 |
+
file_name=file_name,
|
| 857 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 858 |
+
use_container_width=True,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
elif menu == "상담기록 보기":
|
| 862 |
+
st.subheader("📚 저장된 상담기록")
|
| 863 |
+
records = load_records()
|
| 864 |
+
if records.empty:
|
| 865 |
+
st.info("저장된 상담기록이 없습니다.")
|
| 866 |
+
else:
|
| 867 |
+
st.dataframe(records, use_container_width=True)
|
| 868 |
+
|
| 869 |
+
elif menu == "기한 알림":
|
| 870 |
+
st.subheader("⏰ 수급자별 욕구사정·계획서·상담 기한 알림")
|
| 871 |
+
if clients_df.empty:
|
| 872 |
+
st.info("등록된 수급자가 없습니다.")
|
| 873 |
+
else:
|
| 874 |
+
base = st.date_input("기준일", value=date.today())
|
| 875 |
+
rows = []
|
| 876 |
+
for _, c in clients_df.iterrows():
|
| 877 |
+
alerts = due_alerts(safe(c, "admission_date"), base, safe(c, "recognition_end_date"))
|
| 878 |
+
important = [a for a in alerts if "경과" in a or "남음 →" in a]
|
| 879 |
+
rows.append({
|
| 880 |
+
"수급자": safe(c, "masked_name"),
|
| 881 |
+
"등급": safe(c, "care_grade"),
|
| 882 |
+
"기관유형": safe(c, "institution_type"),
|
| 883 |
+
"이용시작일": safe(c, "admission_date"),
|
| 884 |
+
"인정종료일": safe(c, "recognition_end_date"),
|
| 885 |
+
"중요알림": "\n".join(important) if important else "긴급 알림 없음",
|
| 886 |
+
"전체알림": "\n".join(alerts),
|
| 887 |
+
})
|
| 888 |
+
alert_df = pd.DataFrame(rows)
|
| 889 |
+
st.dataframe(alert_df, use_container_width=True)
|
| 890 |
+
|
| 891 |
+
st.caption("통합연동 상담일지 생성기")
|