Delete app.py
Browse files
app.py
DELETED
|
@@ -1,1411 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sqlite3
|
| 3 |
-
import random
|
| 4 |
-
from io import BytesIO
|
| 5 |
-
from datetime import date, datetime, timedelta
|
| 6 |
-
import tempfile
|
| 7 |
-
|
| 8 |
-
import pandas as pd
|
| 9 |
-
import streamlit as st
|
| 10 |
-
from openpyxl import Workbook
|
| 11 |
-
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
|
| 12 |
-
from openpyxl.utils import get_column_letter
|
| 13 |
-
from openpyxl.drawing.image import Image as XLImage
|
| 14 |
-
from openpyxl.worksheet.pagebreak import Break
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
# =========================================================
|
| 18 |
-
# 통합연동 사례관리 생성기
|
| 19 |
-
# Client Center + 상담일지 + 욕구사정 연동형
|
| 20 |
-
# =========================================================
|
| 21 |
-
|
| 22 |
-
st.set_page_config(page_title="통합 사례관리", page_icon="📋", layout="wide")
|
| 23 |
-
|
| 24 |
-
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 25 |
-
|
| 26 |
-
DB_CANDIDATES = [
|
| 27 |
-
"/app/data/clients.db",
|
| 28 |
-
os.path.join(CURRENT_DIR, "..", "수급자등록", "data", "clients.db"),
|
| 29 |
-
os.path.join(CURRENT_DIR, "..", "Client Center", "data", "clients.db"),
|
| 30 |
-
os.path.join(CURRENT_DIR, "..", "ClientCenter", "data", "clients.db"),
|
| 31 |
-
os.path.join(CURRENT_DIR, "..", "Client_Center", "data", "clients.db"),
|
| 32 |
-
os.path.join(CURRENT_DIR, "data", "clients.db"),
|
| 33 |
-
]
|
| 34 |
-
|
| 35 |
-
DB_PATH = None
|
| 36 |
-
for p in DB_CANDIDATES:
|
| 37 |
-
if os.path.exists(p):
|
| 38 |
-
DB_PATH = p
|
| 39 |
-
break
|
| 40 |
-
|
| 41 |
-
if DB_PATH is None:
|
| 42 |
-
os.makedirs(os.path.join(CURRENT_DIR, "data"), exist_ok=True)
|
| 43 |
-
DB_PATH = os.path.join(CURRENT_DIR, "data", "clients.db")
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
# -----------------------------
|
| 47 |
-
# UI 디자인
|
| 48 |
-
# -----------------------------
|
| 49 |
-
st.markdown("""
|
| 50 |
-
<style>
|
| 51 |
-
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Noto+Sans+KR:wght@300;400;500;700;900&display=swap');
|
| 52 |
-
|
| 53 |
-
html, body, [class*="css"], .stApp {
|
| 54 |
-
font-family: 'Inter', 'Noto Sans KR', sans-serif;
|
| 55 |
-
background-color: #fbf9f5;
|
| 56 |
-
color: #1b1c1a;
|
| 57 |
-
}
|
| 58 |
-
.block-container {
|
| 59 |
-
max-width: 1180px;
|
| 60 |
-
padding-top: 1.5rem;
|
| 61 |
-
padding-bottom: 3rem;
|
| 62 |
-
}
|
| 63 |
-
.hero {
|
| 64 |
-
background: linear-gradient(135deg, #f5e6d3, #efe0cd);
|
| 65 |
-
border: 1px solid #ccc3d8;
|
| 66 |
-
border-left: 9px solid #7c3aed;
|
| 67 |
-
border-radius: 24px;
|
| 68 |
-
padding: 34px 36px;
|
| 69 |
-
margin-bottom: 24px;
|
| 70 |
-
box-shadow: 0px 10px 30px rgba(124, 58, 237, 0.04);
|
| 71 |
-
text-align: left;
|
| 72 |
-
}
|
| 73 |
-
.hero h1 {
|
| 74 |
-
margin: 0;
|
| 75 |
-
font-size: clamp(28px, 3.5vw, 42px);
|
| 76 |
-
line-height: 1.2;
|
| 77 |
-
color: #630ed4;
|
| 78 |
-
font-weight: 800;
|
| 79 |
-
}
|
| 80 |
-
.hero p {
|
| 81 |
-
margin: 12px 0 0;
|
| 82 |
-
font-size: 16px;
|
| 83 |
-
color: #4a4455;
|
| 84 |
-
line-height: 1.6;
|
| 85 |
-
}
|
| 86 |
-
.notice {
|
| 87 |
-
background: #ffffff;
|
| 88 |
-
border: 1px solid #e4e2de;
|
| 89 |
-
border-left: 7px solid #606c38;
|
| 90 |
-
border-radius: 16px;
|
| 91 |
-
padding: 16px 18px;
|
| 92 |
-
margin-bottom: 22px;
|
| 93 |
-
font-size: 14.5px;
|
| 94 |
-
line-height: 1.6;
|
| 95 |
-
color: #4a4455;
|
| 96 |
-
box-shadow: 0px 4px 12px rgba(96, 108, 56, 0.02);
|
| 97 |
-
}
|
| 98 |
-
.okbox {
|
| 99 |
-
background: #f4fcf6;
|
| 100 |
-
border: 1px solid #d2ecd9;
|
| 101 |
-
border-left: 8px solid #606c38;
|
| 102 |
-
padding: 16px 18px;
|
| 103 |
-
border-radius: 16px;
|
| 104 |
-
margin-bottom: 14px;
|
| 105 |
-
color: #2b472a;
|
| 106 |
-
font-size: 15px;
|
| 107 |
-
}
|
| 108 |
-
.warnbox {
|
| 109 |
-
background: #fffbf4;
|
| 110 |
-
border: 1px solid #fce8c8;
|
| 111 |
-
border-left: 8px solid #d98b2b;
|
| 112 |
-
padding: 16px 18px;
|
| 113 |
-
border-radius: 16px;
|
| 114 |
-
margin-bottom: 14px;
|
| 115 |
-
color: #5c3f1b;
|
| 116 |
-
font-size: 15px;
|
| 117 |
-
}
|
| 118 |
-
div[data-testid="stMetric"] {
|
| 119 |
-
background: #ffffff;
|
| 120 |
-
border: 1px solid #e4e2de;
|
| 121 |
-
border-radius: 16px;
|
| 122 |
-
padding: 14px;
|
| 123 |
-
box-shadow: 0px 6px 18px rgba(0, 0, 0, 0.01);
|
| 124 |
-
}
|
| 125 |
-
div[data-testid="stMetric"] label,
|
| 126 |
-
div[data-testid="stMetric"] [data-testid="stMetricLabel"] {
|
| 127 |
-
color: #7b7487 !important;
|
| 128 |
-
font-size: 13px !important;
|
| 129 |
-
font-weight: 600 !important;
|
| 130 |
-
}
|
| 131 |
-
div[data-testid="stMetric"] [data-testid="stMetricValue"] {
|
| 132 |
-
color: #630ed4 !important;
|
| 133 |
-
font-size: 22px !important;
|
| 134 |
-
font-weight: 700 !important;
|
| 135 |
-
}
|
| 136 |
-
.stTextInput input, .stTextArea textarea, .stSelectbox div, .stMultiSelect div {
|
| 137 |
-
font-size: 15px !important;
|
| 138 |
-
}
|
| 139 |
-
input, textarea {
|
| 140 |
-
border-radius: 12px !important;
|
| 141 |
-
border: 1px solid #e4e2de !important;
|
| 142 |
-
background: #ffffff !important;
|
| 143 |
-
color: #1b1c1a !important;
|
| 144 |
-
}
|
| 145 |
-
.stButton > button {
|
| 146 |
-
border-radius: 12px !important;
|
| 147 |
-
background: linear-gradient(135deg, #7c3aed, #630ed4) !important;
|
| 148 |
-
color: #ffffff !important;
|
| 149 |
-
font-weight: 700 !important;
|
| 150 |
-
border: none !important;
|
| 151 |
-
padding: 10px 24px !important;
|
| 152 |
-
min-height: 46px !important;
|
| 153 |
-
box-shadow: 0px 4px 12px rgba(124, 58, 237, 0.2) !important;
|
| 154 |
-
transition: all 0.2s ease-in-out !important;
|
| 155 |
-
width: 100% !important;
|
| 156 |
-
}
|
| 157 |
-
.stButton > button:hover {
|
| 158 |
-
transform: translateY(-1px) !important;
|
| 159 |
-
box-shadow: 0px 6px 16px rgba(124, 58, 237, 0.3) !important;
|
| 160 |
-
}
|
| 161 |
-
.stDownloadButton > button {
|
| 162 |
-
border-radius: 12px !important;
|
| 163 |
-
background: #ffffff !important;
|
| 164 |
-
color: #7c3aed !important;
|
| 165 |
-
font-weight: 700 !important;
|
| 166 |
-
border: 1.5px solid #7c3aed !important;
|
| 167 |
-
padding: 10px 24px !important;
|
| 168 |
-
min-height: 46px !important;
|
| 169 |
-
transition: all 0.2s ease-in-out !important;
|
| 170 |
-
width: 100% !important;
|
| 171 |
-
}
|
| 172 |
-
.stDownloadButton > button:hover {
|
| 173 |
-
background: #f3e8ff !important;
|
| 174 |
-
color: #630ed4 !important;
|
| 175 |
-
}
|
| 176 |
-
</style>
|
| 177 |
-
""", unsafe_allow_html=True)
|
| 178 |
-
|
| 179 |
-
st.markdown("""
|
| 180 |
-
<div class="hero">
|
| 181 |
-
<h1>📋 통합 사례관리 생성기</h1>
|
| 182 |
-
<p>수급자 정보, 상담일지, 욕구사정 내용을 연결하여 1차 계획회의록과 2차 결과회의록을 생성합니다.</p>
|
| 183 |
-
</div>
|
| 184 |
-
""", unsafe_allow_html=True)
|
| 185 |
-
|
| 186 |
-
st.markdown("""
|
| 187 |
-
<div class="notice">
|
| 188 |
-
<strong>연동 구조:</strong> Client Center 수급자 DB → 상담기록 → 욕구사정 요약 → 사례관리 1차 계획 → 역할별 시행과정 → 2차 결과평가
|
| 189 |
-
</div>
|
| 190 |
-
""", unsafe_allow_html=True)
|
| 191 |
-
|
| 192 |
-
st.markdown("""
|
| 193 |
-
<div class="notice">
|
| 194 |
-
※ 생성된 문서는 그대로 사용하셔도 되며, 기관의 운영방침, 수급자 상태, 보호자 의견 및 평가기준에 따라 추가 보완사항은 얼마든지 수정 가능합니다. 기관의 상황에 맞게 활용하시기 바랍니다.
|
| 195 |
-
</div>
|
| 196 |
-
""", unsafe_allow_html=True)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
# -----------------------------
|
| 200 |
-
# DB
|
| 201 |
-
# -----------------------------
|
| 202 |
-
def get_conn():
|
| 203 |
-
return sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
def init_db():
|
| 207 |
-
conn = get_conn()
|
| 208 |
-
cur = conn.cursor()
|
| 209 |
-
|
| 210 |
-
cur.execute("""
|
| 211 |
-
CREATE TABLE IF NOT EXISTS clients (
|
| 212 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 213 |
-
name TEXT NOT NULL,
|
| 214 |
-
masked_name TEXT,
|
| 215 |
-
gender TEXT,
|
| 216 |
-
birth_year TEXT,
|
| 217 |
-
care_grade TEXT,
|
| 218 |
-
institution_type TEXT,
|
| 219 |
-
institution_name TEXT,
|
| 220 |
-
admission_date TEXT,
|
| 221 |
-
main_condition TEXT,
|
| 222 |
-
cognitive_status TEXT,
|
| 223 |
-
mobility_status TEXT,
|
| 224 |
-
diet_status TEXT,
|
| 225 |
-
toileting_status TEXT,
|
| 226 |
-
guardian_name TEXT,
|
| 227 |
-
guardian_phone TEXT,
|
| 228 |
-
notes TEXT,
|
| 229 |
-
status TEXT DEFAULT '이용중',
|
| 230 |
-
created_at TEXT,
|
| 231 |
-
updated_at TEXT
|
| 232 |
-
)
|
| 233 |
-
""")
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
new_client_columns = {
|
| 237 |
-
"recognition_number": "TEXT",
|
| 238 |
-
"recognition_start_date": "TEXT",
|
| 239 |
-
"recognition_end_date": "TEXT",
|
| 240 |
-
"previous_care_grade": "TEXT",
|
| 241 |
-
"plan_change_required": "TEXT DEFAULT '아니오'",
|
| 242 |
-
"plan_change_type": "TEXT",
|
| 243 |
-
"plan_change_reason": "TEXT",
|
| 244 |
-
"plan_change_date": "TEXT",
|
| 245 |
-
"plan_rewrite_status": "TEXT DEFAULT '해당없음'",
|
| 246 |
-
"linked_document": "TEXT",
|
| 247 |
-
}
|
| 248 |
-
cur.execute("PRAGMA table_info(clients)")
|
| 249 |
-
existing_client_cols = [row[1] for row in cur.fetchall()]
|
| 250 |
-
for col, col_type in new_client_columns.items():
|
| 251 |
-
if col not in existing_client_cols:
|
| 252 |
-
cur.execute(f"ALTER TABLE clients ADD COLUMN {col} {col_type}")
|
| 253 |
-
|
| 254 |
-
cur.execute("""
|
| 255 |
-
CREATE TABLE IF NOT EXISTS counseling_records (
|
| 256 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 257 |
-
client_id INTEGER,
|
| 258 |
-
client_masked_name TEXT,
|
| 259 |
-
institution_type TEXT,
|
| 260 |
-
counseling_type TEXT,
|
| 261 |
-
counseling_date TEXT,
|
| 262 |
-
counselor TEXT,
|
| 263 |
-
counseling_reason TEXT,
|
| 264 |
-
client_status_change TEXT,
|
| 265 |
-
guardian_opinion TEXT,
|
| 266 |
-
counseling_content TEXT,
|
| 267 |
-
action_plan TEXT,
|
| 268 |
-
evaluation_score INTEGER,
|
| 269 |
-
missing_items TEXT,
|
| 270 |
-
compliance_result TEXT,
|
| 271 |
-
next_due_note TEXT,
|
| 272 |
-
created_at TEXT
|
| 273 |
-
)
|
| 274 |
-
""")
|
| 275 |
-
|
| 276 |
-
cur.execute("""
|
| 277 |
-
CREATE TABLE IF NOT EXISTS needs_assessment_records (
|
| 278 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 279 |
-
client_id INTEGER,
|
| 280 |
-
client_masked_name TEXT,
|
| 281 |
-
assessment_date TEXT,
|
| 282 |
-
total_opinion TEXT,
|
| 283 |
-
result_status TEXT,
|
| 284 |
-
result_plan TEXT,
|
| 285 |
-
fall_risk TEXT,
|
| 286 |
-
bedsore_risk TEXT,
|
| 287 |
-
dementia_status TEXT,
|
| 288 |
-
diaper_use TEXT,
|
| 289 |
-
service_needs TEXT,
|
| 290 |
-
created_at TEXT
|
| 291 |
-
)
|
| 292 |
-
""")
|
| 293 |
-
|
| 294 |
-
cur.execute("""
|
| 295 |
-
CREATE TABLE IF NOT EXISTS case_management_records (
|
| 296 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 297 |
-
client_id INTEGER,
|
| 298 |
-
client_masked_name TEXT,
|
| 299 |
-
institution_type TEXT,
|
| 300 |
-
case_type TEXT,
|
| 301 |
-
first_meeting_date TEXT,
|
| 302 |
-
second_meeting_date TEXT,
|
| 303 |
-
selection_reason TEXT,
|
| 304 |
-
first_plan TEXT,
|
| 305 |
-
implementation_process TEXT,
|
| 306 |
-
second_result TEXT,
|
| 307 |
-
evaluation_score INTEGER,
|
| 308 |
-
missing_items TEXT,
|
| 309 |
-
created_at TEXT
|
| 310 |
-
)
|
| 311 |
-
""")
|
| 312 |
-
|
| 313 |
-
conn.commit()
|
| 314 |
-
conn.close()
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
def load_clients():
|
| 318 |
-
conn = get_conn()
|
| 319 |
-
try:
|
| 320 |
-
df = pd.read_sql_query("""
|
| 321 |
-
SELECT * FROM clients ORDER BY id DESC LIMIT 300
|
| 322 |
-
""", conn)
|
| 323 |
-
if not df.empty and "care_grade" in df.columns:
|
| 324 |
-
df["care_grade"] = df["care_grade"].apply(lambda x: str(x).strip() + "등급" if str(x).strip() in ["1", "2", "3", "4", "5"] else str(x).strip())
|
| 325 |
-
except Exception:
|
| 326 |
-
df = pd.DataFrame()
|
| 327 |
-
conn.close()
|
| 328 |
-
return df
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
def load_counseling(client_id):
|
| 332 |
-
conn = get_conn()
|
| 333 |
-
try:
|
| 334 |
-
df = pd.read_sql_query("""
|
| 335 |
-
SELECT * FROM counseling_records
|
| 336 |
-
WHERE client_id = ?
|
| 337 |
-
ORDER BY counseling_date DESC, id DESC
|
| 338 |
-
""", conn, params=(int(client_id),))
|
| 339 |
-
except Exception:
|
| 340 |
-
df = pd.DataFrame()
|
| 341 |
-
conn.close()
|
| 342 |
-
return df
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
def load_needs_assessment(client_id):
|
| 346 |
-
conn = get_conn()
|
| 347 |
-
try:
|
| 348 |
-
df = pd.read_sql_query("""
|
| 349 |
-
SELECT * FROM needs_assessment_records
|
| 350 |
-
WHERE client_id = ?
|
| 351 |
-
ORDER BY assessment_date DESC, id DESC
|
| 352 |
-
""", conn, params=(int(client_id),))
|
| 353 |
-
except Exception:
|
| 354 |
-
df = pd.DataFrame()
|
| 355 |
-
conn.close()
|
| 356 |
-
return df
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
def save_case_record(data):
|
| 360 |
-
conn = get_conn()
|
| 361 |
-
cur = conn.cursor()
|
| 362 |
-
cur.execute("""
|
| 363 |
-
INSERT INTO case_management_records (
|
| 364 |
-
client_id, client_masked_name, institution_type, case_type,
|
| 365 |
-
first_meeting_date, second_meeting_date, selection_reason,
|
| 366 |
-
first_plan, implementation_process, second_result,
|
| 367 |
-
evaluation_score, missing_items, created_at
|
| 368 |
-
)
|
| 369 |
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 370 |
-
""", (
|
| 371 |
-
data["client_id"], data["client_masked_name"], data["institution_type"], data["case_type"],
|
| 372 |
-
data["first_meeting_date"], data["second_meeting_date"], data["selection_reason"],
|
| 373 |
-
data["first_plan"], data["implementation_process"], data["second_result"],
|
| 374 |
-
data["evaluation_score"], data["missing_items"],
|
| 375 |
-
datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 376 |
-
))
|
| 377 |
-
conn.commit()
|
| 378 |
-
conn.close()
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
def normalize_date_text(value):
|
| 384 |
-
"""Client Center 날짜 형식을 YYYY-MM-DD로 안전하게 맞춥니다."""
|
| 385 |
-
v = str(value or "").strip()
|
| 386 |
-
if not v or v.lower() == "nan":
|
| 387 |
-
return ""
|
| 388 |
-
try:
|
| 389 |
-
return pd.to_datetime(v, errors="raise").strftime("%Y-%m-%d")
|
| 390 |
-
except Exception:
|
| 391 |
-
return v
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
def days_until(date_text):
|
| 395 |
-
v = normalize_date_text(date_text)
|
| 396 |
-
if not v:
|
| 397 |
-
return None
|
| 398 |
-
try:
|
| 399 |
-
return (datetime.strptime(v, "%Y-%m-%d").date() - date.today()).days
|
| 400 |
-
except Exception:
|
| 401 |
-
return None
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
def recognition_alert_text(end_date_text):
|
| 405 |
-
days = days_until(end_date_text)
|
| 406 |
-
if days is None:
|
| 407 |
-
return "인정기간 종료일 미입력"
|
| 408 |
-
if days < 0:
|
| 409 |
-
return f"인정기간 만료 {abs(days)}일 경과"
|
| 410 |
-
if days <= 30:
|
| 411 |
-
return f"만료 {days}일 전: 급여계획 재검토 필요"
|
| 412 |
-
if days <= 90:
|
| 413 |
-
return f"만료 {days}일 전: 갱신/계획 확인"
|
| 414 |
-
return f"만료 {days}일 전"
|
| 415 |
-
|
| 416 |
-
def safe(row, key, default=""):
|
| 417 |
-
try:
|
| 418 |
-
v = row.get(key, default)
|
| 419 |
-
if pd.isna(v):
|
| 420 |
-
return default
|
| 421 |
-
return str(v)
|
| 422 |
-
except Exception:
|
| 423 |
-
return default
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
def mask_name(name):
|
| 427 |
-
name = str(name or "").strip()
|
| 428 |
-
if len(name) >= 3:
|
| 429 |
-
return name[0] + "○" + name[2:]
|
| 430 |
-
if len(name) == 2:
|
| 431 |
-
return name[0] + "○"
|
| 432 |
-
return name
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
init_db()
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
# -----------------------------
|
| 439 |
-
# 사례 유형
|
| 440 |
-
# -----------------------------
|
| 441 |
-
CASE_TYPES = {
|
| 442 |
-
"낙상 고위험 관리": {
|
| 443 |
-
"reason": "이동 중 불안정, 화장실 이동 위험, 보행보조 필요 등 낙상 위험요인이 확인되어 사례관리가 필요함.",
|
| 444 |
-
"goal": "낙상 사고를 예방하고 안전한 이동과 생활환경을 유지한다.",
|
| 445 |
-
"keywords": ["낙상예방", "이동보조", "환경정비", "화장실 동행", "보행상태 관찰"],
|
| 446 |
-
},
|
| 447 |
-
"식사량 감소·영양관리": {
|
| 448 |
-
"reason": "식사량 감소, 수분섭취 부족, 체중저하 우려가 확인되어 영양상태 관리를 위한 사례관리가 필요함.",
|
| 449 |
-
"goal": "식사량과 수분섭취를 안정적으로 유지하고 영양 저하 위험을 예방한다.",
|
| 450 |
-
"keywords": ["식사보조", "수분섭취", "선호음식", "연하상태", "섭취량 기록"],
|
| 451 |
-
},
|
| 452 |
-
"인지저하·정서불안": {
|
| 453 |
-
"reason": "반복질문, 의심표현, 불안감, 정서적 위축 등 인지·정서 변화가 확인되어 지속 관찰과 개별 대응이 필요함.",
|
| 454 |
-
"goal": "불안감을 완화하고 안정적인 일상생활과 서비스 이용이 이루어지도록 지원한다.",
|
| 455 |
-
"keywords": ["정서지원", "인지활동", "반복설명", "안정적 환경", "보호자 상담"],
|
| 456 |
-
},
|
| 457 |
-
"욕창·피부상태 관리": {
|
| 458 |
-
"reason": "기저귀 착용, 활동량 저하, 피부 발적 또는 욕창 위험이 확인되어 피부상태 관찰과 예방관리가 필요함.",
|
| 459 |
-
"goal": "피부 청결과 안위를 유지하고 욕창 발생을 예방한다.",
|
| 460 |
-
"keywords": ["피부관찰", "체위변경", "기저귀케어", "보습", "간호관찰"],
|
| 461 |
-
},
|
| 462 |
-
"프로그램 참여 저하": {
|
| 463 |
-
"reason": "프로그램 참여 감소, 무기력, 대화 회피 등 사회적·정서적 위축이 관찰되어 사례관리가 필요함.",
|
| 464 |
-
"goal": "선호 활동 중심으로 참여를 유도하고 사회적 관계와 활력을 높인다.",
|
| 465 |
-
"keywords": ["선호활동", "참여격려", "정서지원", "프로그램 조정", "참여도 기록"],
|
| 466 |
-
},
|
| 467 |
-
"보호자 요청·서비스 조정": {
|
| 468 |
-
"reason": "보호자 요청 또는 서비스 조정 필요성이 확인되어 급여제공 방향 재검토와 사례관리가 필요함.",
|
| 469 |
-
"goal": "보호자 의견과 수급자 상태를 반영하여 적절한 서비스 제공 방향을 조정한다.",
|
| 470 |
-
"keywords": ["보호자 상담", "서비스 조정", "급여계획 반영", "종사자 공유", "후속상담"],
|
| 471 |
-
},
|
| 472 |
-
}
|
| 473 |
-
|
| 474 |
-
# -----------------------------
|
| 475 |
-
# 개인별이용계획 지원방법 데이터베이스
|
| 476 |
-
# -----------------------------
|
| 477 |
-
CASE_DETAILS = {
|
| 478 |
-
"낙상 고위험 관리": {
|
| 479 |
-
"domains": ["건강/신체", "환경", "복약"],
|
| 480 |
-
"goal": "낙상 사고를 예방하고 안전한 이동과 생활환경을 유지함.",
|
| 481 |
-
"subjective": "수급자 및 보호자는 최근 보행 시 다리에 힘이 풀리거나 어지럼증이 자주 발생하여 이동 시 불안감이 매우 크다고 호소함. 특히 화장실 이동 시 미끄러질까 걱정된다고 전함.",
|
| 482 |
-
"objective": "보행보조기를 사용하더라도 걸음걸이가 매우 불안정하고 어지럼증을 종종 관찰함. 생활실 바닥에 전선이나 문턱이 있어 낙상 위험요소로 작용하는 것을 확인하고 관찰함.",
|
| 483 |
-
"assessment": "수급자의 하지 근력 저하와 인지 저하 상태를 고려할 때 낙상 위험도가 높은 상태로 사정됨. 다리에 힘이 빠지거나 어지러움 호소 시 즉시 부축하고 안전한 보행을 위한 개별 지원방법을 조속히 연계 및 계획함.",
|
| 484 |
-
"plan": [
|
| 485 |
-
"보행 시 부축을 제공함.",
|
| 486 |
-
"미끄럼 방지 환경을 점검함.",
|
| 487 |
-
"침상 난간 상태를 확인함.",
|
| 488 |
-
"야간 이동 시 안전관찰을 실시함.",
|
| 489 |
-
"이동 전 어지럼 여부를 확인함.",
|
| 490 |
-
"보행보조기 사용을 안내함.",
|
| 491 |
-
"실내 정리정돈 상태를 점검함.",
|
| 492 |
-
"화장실 이동 시 동행 및 안전관찰을 실시함."
|
| 493 |
-
],
|
| 494 |
-
"resource": "보건소 낙상예방 프로그램 안내 및 방문간호 서비스 연계를 검토함."
|
| 495 |
-
},
|
| 496 |
-
"식사량 감소·영양관리": {
|
| 497 |
-
"domains": ["건강/신체", "가족부담"],
|
| 498 |
-
"goal": "식사량과 수분섭취를 안정적으로 유지하고 영양 저하 위험을 예방함.",
|
| 499 |
-
"subjective": "수급자는 입맛이 전혀 없다고 호소하며 식사를 거부하거나 반 공기도 채 먹지 못한다고 표현함. 보호자는 체중 저하와 전신 쇠약 우려로 영양 관리에 대해 깊은 염려를 표함.",
|
| 500 |
-
"objective": "최근 식사량이 눈에 띄게 감소하여 평균 섭취량이 기존 대비 50% 미만으로 확인됨. 연하곤란이나 구강 건조가 관찰되며 체중이 소폭 감소한 것이 확인됨.",
|
| 501 |
-
"assessment": "불안정한 섭취 지속 시 만성적인 영양결핍 및 면역 저하 위험이 매우 큰 상태로 판단됨. 수급자의 선호 음식 반영 및 수분 섭취 유도 등 구체적인 영양 보충 지원을 계획함.",
|
| 502 |
-
"plan": [
|
| 503 |
-
"선호 음식을 확인함.",
|
| 504 |
-
"기호식을 반영함.",
|
| 505 |
-
"수분섭취를 독려함.",
|
| 506 |
-
"영양상태를 관찰함.",
|
| 507 |
-
"체중변화를 확인함.",
|
| 508 |
-
"영양보충을 지원함."
|
| 509 |
-
],
|
| 510 |
-
"resource": "지역 보건소 영양 보충 프로그램 참여 및 필요 시 영양 수액 처방을 위한 병원 연계를 검토함."
|
| 511 |
-
},
|
| 512 |
-
"인지저하·정서불안": {
|
| 513 |
-
"domains": ["인지/치매", "정서/심리", "인권"],
|
| 514 |
-
"goal": "불안감을 완화하고 안정적인 일상생활과 서비스 이용이 이루어지도록 지원함.",
|
| 515 |
-
"subjective": "수급자는 본인의 물건을 남이 가져갔다고 자주 주장하며 반복하여 질문하고 의심을 표함. 불안감으로 인해 다른 사람들과 대화하지 않겠다고 극도의 스트레스를 호소함.",
|
| 516 |
-
"objective": "시간, 장소, 사람에 대한 인지 지남력 저하가 관찰됨. 주변 자극이 있을 때 방어적으로 흥분하거나 동일한 질문을 반복적으로 수행하고 배회하는 경향이 관찰됨.",
|
| 517 |
-
"assessment": "치매 증상 진행에 따른 일시적 망상 및 배회 행동으로 사정됨. 정면 반박을 피하고 안정감을 주는 말벗 지원과 익숙한 환경 유지를 병행하여 심리적 안정을 도모해야 한다고 판단됨.",
|
| 518 |
-
"plan": [
|
| 519 |
-
"날짜와 장소를 반복 안내함.",
|
| 520 |
-
"회상대화를 실시함.",
|
| 521 |
-
"익숙한 환경을 유지하도록 지원함.",
|
| 522 |
-
"인지자극 활동을 제공함.",
|
| 523 |
-
"동일 질문에 안정적으로 응대함.",
|
| 524 |
-
"망상 시 ���면 반박을 지양함.",
|
| 525 |
-
"감정을 공감함.",
|
| 526 |
-
"화제를 전환함."
|
| 527 |
-
],
|
| 528 |
-
"resource": "치매안심센터 치매가족 지원 서비스 및 인지 자극 프로그램 연계를 검토함."
|
| 529 |
-
},
|
| 530 |
-
"욕창·피부상태 관리": {
|
| 531 |
-
"domains": ["건강/신체", "복약"],
|
| 532 |
-
"goal": "피부 청결과 안위를 유지하고 욕창 발생을 예방함.",
|
| 533 |
-
"subjective": "수급자는 하루 종일 꼬리뼈와 엉덩이 부위가 뻐근하고 가렵다고 호소함. 기저귀 착용으로 땀이 차서 피부가 따갑다고 불만을 표현함.",
|
| 534 |
-
"objective": "와상 상태로 활동량이 거의 없으며 미골 부위에 가벼운 발적이 관찰됨. 기저귀 교체가 빈번하고 피부가 습윤한 상태가 지속적으로 확인됨.",
|
| 535 |
-
"assessment": "혈액순환 저하 및 습윤 환경으로 인한 초기 욕창 진행 단계로 판단됨. 정기적인 체위변경과 엄격한 피부 청결 관리가 시급하며 단백질 영양 보충이 필요하다고 사정됨.",
|
| 536 |
-
"plan": [
|
| 537 |
-
"정기적 체위변경을 실시함.",
|
| 538 |
-
"피부상태를 확인함.",
|
| 539 |
-
"욕창 발생 여부를 관찰함.",
|
| 540 |
-
"영양상태를 확인함.",
|
| 541 |
-
"장시간 동일 자세를 예방함.",
|
| 542 |
-
"피부 청결을 유지함."
|
| 543 |
-
],
|
| 544 |
-
"resource": "욕창 드레싱 및 피부 소독을 위한 방문간호 서비스 연계를 검토함."
|
| 545 |
-
},
|
| 546 |
-
"프로그램 참여 저하": {
|
| 547 |
-
"domains": ["정서/심리", "사회고립"],
|
| 548 |
-
"goal": "선호 활동 중심으로 참여를 유도하고 사회적 관계와 활력을 높임.",
|
| 549 |
-
"subjective": "수급자는 단체 프로그램에 참여하는 것이 귀찮고 피곤하다고 호소함. 다른 수급자들과 어울리지 않고 생활실에 혼자 남아 있기를 고집하며 외로움을 간접적으로 호소함.",
|
| 550 |
-
"objective": "최근 2주간 프로그램 참여 기록이 현저히 저저함. 사람들과의 시선 마주침을 피하고 하루 대부분의 시간을 침상이나 휠체어에 무기력하게 앉아 있는 상태로 확인됨.",
|
| 551 |
-
"assessment": "정서적 위축과 우울증상으로 인한 사회적 고립 상태로 판단됨. 억지로 프로그램 참여를 강요하기보다는 선호도가 높은 소규모 활동 및 일대일 말벗 지원을 통해 대인관계 및 활력을 촉진하도록 계획함.",
|
| 552 |
-
"plan": [
|
| 553 |
-
"집단 프로그램 참여를 지원함.",
|
| 554 |
-
"또래 관계 형성을 지원함.",
|
| 555 |
-
"대화 기회를 제공함.",
|
| 556 |
-
"공동활동 참여를 유도함.",
|
| 557 |
-
"말벗 서비스를 제공함.",
|
| 558 |
-
"취미활동 참여를 지원함.",
|
| 559 |
-
"성취감을 경험하도록 지원함."
|
| 560 |
-
],
|
| 561 |
-
"resource": "지역 복지관 프로그램 및 정서 지원 멘토링 연계를 검토함."
|
| 562 |
-
},
|
| 563 |
-
"보호자 요청·서비스 조정": {
|
| 564 |
-
"domains": ["갈등", "가족부담", "지역자원"],
|
| 565 |
-
"goal": "보호자 의견과 수급자 상태를 반영하여 적절한 서비스 제공 방향을 조정함.",
|
| 566 |
-
"subjective": "보호자는 수급자의 갑작스러운 상태 악화로 인한 집안 내 돌봄 스트레스와 고충을 호소함. 서비스 이용 요일 및 시간을 추가하거나 변경해 줄 것을 강력하게 요청함.",
|
| 567 |
-
"objective": "수급자의 인지/신체 저하 속도가 빨라져 기존 급여제공계획서의 시간 조율이 맞지 않음을 관찰함. 가족 간 돌봄 역할 분담 갈등이 표면화된 것을 상담기록으로 확인함.",
|
| 568 |
-
"assessment": "보호자의 돌봄 부담 완화를 위해 급여시간 유연화와 외부 복지 서비스 활용 방안이 시급하게 요구되는 상황으로 판단됨. 보호자 상담을 통한 의견 조정 및 급여제공계획 변경을 검토함.",
|
| 569 |
-
"plan": [
|
| 570 |
-
"보호자 상담을 실시함.",
|
| 571 |
-
"돌봄 부담을 경청함.",
|
| 572 |
-
"지역자원 연계를 안내함.",
|
| 573 |
-
"가족 의견을 조정함.",
|
| 574 |
-
"의사소통을 지원함."
|
| 575 |
-
],
|
| 576 |
-
"resource": "행정복지센터 긴급 돌봄 서비스 및 치매가족 상담 자원 연계를 검토함."
|
| 577 |
-
}
|
| 578 |
-
}
|
| 579 |
-
|
| 580 |
-
OPENERS = [
|
| 581 |
-
"회의 참석자들은 최근 상담기록과 욕구사정 내용을 함께 검토함.",
|
| 582 |
-
"본 사례회의에서는 수급자의 상태 변화, 보호자 의견, 급여제공 중 관찰사항을 종합함.",
|
| 583 |
-
"금일 회의에서는 단순 문제기록이 아니라 실제 서비스 제공 과정에 반영할 개입 방향을 중심으로 논의함.",
|
| 584 |
-
"수급자의 욕구와 기관에서 제공 가능한 자원을 연결하여 사례관리 필요성을 검토함.",
|
| 585 |
-
]
|
| 586 |
-
|
| 587 |
-
TONES = [
|
| 588 |
-
"각 직종별 역할을 명확히 하여 동일한 방향으로 지원하기로 결정함.",
|
| 589 |
-
"상담기록, 욕구사정, 급여제공기록이 서로 연결되도록 관리하기로 계획함.",
|
| 590 |
-
"보호자에게도 주요 변화와 기관의 조치계획을 안내하여 협조를 구하기로 함.",
|
| 591 |
-
"30일 이상 관찰 후 결과를 다시 확인하고 필요 시 급여제공계획을 조정하기로 확인함.",
|
| 592 |
-
]
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
# -----------------------------
|
| 596 |
-
# 요약 생성
|
| 597 |
-
# -----------------------------
|
| 598 |
-
def summarize_counseling(df):
|
| 599 |
-
if df.empty:
|
| 600 |
-
return "저장된 상담일지가 없어 수급자 기본정보와 직접 입력한 상태변화를 중심으로 사례관리 회의를 진행함."
|
| 601 |
-
lines = []
|
| 602 |
-
for _, r in df.head(5).iterrows():
|
| 603 |
-
lines.append(
|
| 604 |
-
f"- {safe(r,'counseling_date')}: {safe(r,'counseling_type')} / 사유: {safe(r,'counseling_reason')} / "
|
| 605 |
-
f"상태변화: {safe(r,'client_status_change') or '기록 없음'} / 보호자 의견: {safe(r,'guardian_opinion') or '기록 없음'}"
|
| 606 |
-
)
|
| 607 |
-
return "\n".join(lines)
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
def summarize_needs(df, client, manual_needs):
|
| 611 |
-
if not df.empty:
|
| 612 |
-
r = df.iloc[0]
|
| 613 |
-
return (
|
| 614 |
-
f"최근 욕구사정일: {safe(r,'assessment_date')}\n"
|
| 615 |
-
f"종합소견: {safe(r,'total_opinion')}\n"
|
| 616 |
-
f"결과/계획: {safe(r,'result_plan')}\n"
|
| 617 |
-
f"위험요인: 낙상 {safe(r,'fall_risk')}, 욕창 {safe(r,'bedsore_risk')}, 인지 {safe(r,'dementia_status')}, 기저귀 {safe(r,'diaper_use')}\n"
|
| 618 |
-
f"서비스 욕구: {safe(r,'service_needs')}"
|
| 619 |
-
)
|
| 620 |
-
|
| 621 |
-
base = (
|
| 622 |
-
f"Client Center 등록정보 기준 인정번호: {safe(client,'recognition_number') or '미입력'}, 인정기간: {safe(client,'recognition_start_date') or '미입력'} ~ {safe(client,'recognition_end_date') or '미입력'}, 주요상태: {safe(client,'main_condition') or '기록 없음'}, "
|
| 623 |
-
f"인지상태: {safe(client,'cognitive_status') or '기록 없음'}, "
|
| 624 |
-
f"이동상태: {safe(client,'mobility_status') or '기록 없음'}, "
|
| 625 |
-
f"식사상태: {safe(client,'diet_status') or '기록 없음'}, "
|
| 626 |
-
f"배변/배뇨상태: {safe(client,'toileting_status') or '기록 없음'}"
|
| 627 |
-
)
|
| 628 |
-
if manual_needs.strip():
|
| 629 |
-
base += "\n직접 입력 욕구사정 요약: " + manual_needs.strip()
|
| 630 |
-
return base
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
# -----------------------------
|
| 634 |
-
# 사례유형 자동추천 및 리스크 분석
|
| 635 |
-
# -----------------------------
|
| 636 |
-
def recommend_case_type(counseling_summary, needs_summary, main_condition):
|
| 637 |
-
text = f"{counseling_summary} {needs_summary} {main_condition}".lower()
|
| 638 |
-
scores = {
|
| 639 |
-
"낙상 고위험 관리": 0,
|
| 640 |
-
"식사량 감소·영양관리": 0,
|
| 641 |
-
"인지저하·정서불안": 0,
|
| 642 |
-
"욕창·피부상태 관리": 0,
|
| 643 |
-
"프로그램 참여 저하": 0,
|
| 644 |
-
"보호자 요청·서비스 조정": 0
|
| 645 |
-
}
|
| 646 |
-
|
| 647 |
-
keywords = {
|
| 648 |
-
"낙상 고위험 관리": ["낙상", "어지러", "넘어짐", "어지럼", "보행", "휠체어", "이동", "보조기", "안전"],
|
| 649 |
-
"식사량 감소·영양관리": ["식사", "식사량", "영양", "체중", "소화", "섭취", "식욕", "거부", "식단"],
|
| 650 |
-
"인지저하·정서불안": ["인지", "치매", "치매안심", "의심", "훔쳐", "망상", "반복", "BPSD", "지남력", "불안", "배회"],
|
| 651 |
-
"욕창·피부상태 관리": ["욕창", "피부", "발적", "기저귀", "체위", "습윤", "와상", "보습"],
|
| 652 |
-
"프로그램 참여 저하": ["프로그램", "참여", "무기력", "우울", "위축", "말벗", "회피", "활동"],
|
| 653 |
-
"보호자 요청·서비스 조정": ["보호자", "요청", "조정", "갈등", "부담", "가족", "상담", "고충"]
|
| 654 |
-
}
|
| 655 |
-
|
| 656 |
-
for c_type, kw_list in keywords.items():
|
| 657 |
-
for kw in kw_list:
|
| 658 |
-
if kw in text:
|
| 659 |
-
scores[c_type] += 1
|
| 660 |
-
|
| 661 |
-
recommended = max(scores, key=scores.get)
|
| 662 |
-
if scores[recommended] == 0:
|
| 663 |
-
return "낙상 고위험 관리"
|
| 664 |
-
return recommended
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
def analyze_risk_domains(case_type, needs_summary, counseling_summary):
|
| 668 |
-
domains = []
|
| 669 |
-
if "낙상" in case_type or "욕창" in case_type or "식사" in case_type:
|
| 670 |
-
domains.append("건강/신체")
|
| 671 |
-
if "낙상" in case_type:
|
| 672 |
-
domains.append("환경")
|
| 673 |
-
if "식사" in case_type:
|
| 674 |
-
domains.append("건강/신체")
|
| 675 |
-
if "인지저하" in case_type or "치매" in case_type:
|
| 676 |
-
domains.append("인지/치매")
|
| 677 |
-
domains.append("정서/심리")
|
| 678 |
-
if "프로그램" in case_type:
|
| 679 |
-
domains.append("정서/심리")
|
| 680 |
-
domains.append("사회고립")
|
| 681 |
-
if "보호자" in case_type:
|
| 682 |
-
domains.append("갈등")
|
| 683 |
-
domains.append("가족부담")
|
| 684 |
-
|
| 685 |
-
text = (needs_summary + " " + counseling_summary).lower()
|
| 686 |
-
if "약" in text or "복약" in text or "약물" in text:
|
| 687 |
-
domains.append("복약")
|
| 688 |
-
if "보건소" in text or "안심센터" in text or "복지관" in text:
|
| 689 |
-
domains.append("지역자원")
|
| 690 |
-
if "학대" in text or "방임" in text or "인권" in text:
|
| 691 |
-
domains.append("인권")
|
| 692 |
-
|
| 693 |
-
domains = list(dict.fromkeys(domains))
|
| 694 |
-
if not domains:
|
| 695 |
-
domains = ["건강/신체"]
|
| 696 |
-
return domains
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
def build_role_text(case_type, custom_roles=""):
|
| 700 |
-
details = CASE_DETAILS.get(case_type, CASE_DETAILS["낙상 고위험 관리"])
|
| 701 |
-
selected_methods = details["plan"][:3]
|
| 702 |
-
methods_bullet = ", ".join(selected_methods).replace("함.", "함")
|
| 703 |
-
|
| 704 |
-
default = f"""
|
| 705 |
-
시설장: 사례관리 대상 선정의 적절성을 확인하고, 급여제공 계획 변경 및 자원 연계 타당성을 점검함.
|
| 706 |
-
사회복지사: 상담기록과 욕구사정을 토대로 사례개입 방향을 설정하고, {methods_bullet} 등 구체적인 이용계획을 수립하여 제공함.
|
| 707 |
-
요양보호사: 서비스 제공 중 수급자 상태 변화를 관찰하고, {methods_bullet} 조치 사항을 실행하여 급여제공기록지에 상세 기록함.
|
| 708 |
-
간호조무사: 활력징후 및 수급자의 전반적인 건강, 피부 상태를 점검하며, 이상 증상 발생 시 시설장에게 보고함.
|
| 709 |
-
물리치료사: 신체 잔존 기능 유지를 위해 적합한 이동 및 자세 제어 운동 방법 등을 조언함.
|
| 710 |
-
""".strip()
|
| 711 |
-
return custom_roles.strip() or default
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
def build_attendees_text(director, social_worker, caregiver, nurse, therapist, guardian, extra_attendees):
|
| 715 |
-
attendees = []
|
| 716 |
-
if director.strip():
|
| 717 |
-
attendees.append(f"시설장: {director.strip()}")
|
| 718 |
-
else:
|
| 719 |
-
attendees.append("시설장: 참석 또는 검토")
|
| 720 |
-
if social_worker.strip():
|
| 721 |
-
attendees.append(f"사회복지사: {social_worker.strip()}")
|
| 722 |
-
else:
|
| 723 |
-
attendees.append("사회복지사: 참석")
|
| 724 |
-
if caregiver.strip():
|
| 725 |
-
attendees.append(f"요양보호사: {caregiver.strip()}")
|
| 726 |
-
else:
|
| 727 |
-
attendees.append("요양보호사: 참석")
|
| 728 |
-
if nurse.strip():
|
| 729 |
-
attendees.append(f"간호조무사: {nurse.strip()}")
|
| 730 |
-
else:
|
| 731 |
-
attendees.append("간호조무사: 참석")
|
| 732 |
-
if therapist.strip():
|
| 733 |
-
attendees.append(f"물리치료사: {therapist.strip()}")
|
| 734 |
-
else:
|
| 735 |
-
attendees.append("물리치료사: 해당 시 자문")
|
| 736 |
-
if guardian.strip():
|
| 737 |
-
attendees.append(f"보호자: {guardian.strip()}")
|
| 738 |
-
if extra_attendees.strip():
|
| 739 |
-
attendees.append(f"기타 참석자: {extra_attendees.strip()}")
|
| 740 |
-
return "\n".join(attendees)
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
def build_case_documents(client, counseling_summary, needs_summary, case_type, custom_selection, custom_status, custom_goal, custom_roles):
|
| 744 |
-
case = CASE_TYPES[case_type]
|
| 745 |
-
details = CASE_DETAILS.get(case_type, CASE_DETAILS["낙상 고위험 관리"])
|
| 746 |
-
opener = random.choice(OPENERS)
|
| 747 |
-
tone = random.choice(TONES)
|
| 748 |
-
masked = safe(client, "masked_name", "수급자")
|
| 749 |
-
grade = safe(client, "care_grade")
|
| 750 |
-
institution_type = safe(client, "institution_type")
|
| 751 |
-
keywords = ", ".join(case["keywords"])
|
| 752 |
-
|
| 753 |
-
domains = analyze_risk_domains(case_type, needs_summary, counseling_summary)
|
| 754 |
-
domains_str = ", ".join(domains)
|
| 755 |
-
|
| 756 |
-
selection = custom_selection.strip() or (
|
| 757 |
-
f"{masked} 수급자는 {grade} 대상자로 {case['reason'].replace('필요함.', '필요함')} "
|
| 758 |
-
f"상담기록과 욕구사정에서 확인된 상태를 종합할 때 {case_type} 사례관리 대상으로 선정함."
|
| 759 |
-
)
|
| 760 |
-
|
| 761 |
-
first_content = f"""
|
| 762 |
-
{opener}
|
| 763 |
-
|
| 764 |
-
[10대 리스크 도메인 자동분석]
|
| 765 |
-
- 분석 결과 분류된 핵심 리스크 영역: {domains_str}
|
| 766 |
-
|
| 767 |
-
[SOAP 구조화 기록]
|
| 768 |
-
[S 주관적 호소]
|
| 769 |
-
- {details['subjective']}
|
| 770 |
-
|
| 771 |
-
[O 객관적 관찰]
|
| 772 |
-
- {details['objective']}
|
| 773 |
-
|
| 774 |
-
[A 전문적 판단]
|
| 775 |
-
- {details['assessment']}
|
| 776 |
-
|
| 777 |
-
[P 조치계획]
|
| 778 |
-
- {details['resource']}
|
| 779 |
-
|
| 780 |
-
[수급자 기본상태]
|
| 781 |
-
- 기관유형: {institution_type}
|
| 782 |
-
- 장기요양등급: {grade}
|
| 783 |
-
- 인정번호: {safe(client,'recognition_number') or '미입력'}
|
| 784 |
-
- 인정기간: {safe(client,'recognition_start_date') or '미입력'} ~ {safe(client,'recognition_end_date') or '미입력'}
|
| 785 |
-
- 인정기간 알림: {recognition_alert_text(safe(client,'recognition_end_date'))}
|
| 786 |
-
- 주요 질환/상태: {safe(client,'main_condition') or '기록 없음'}
|
| 787 |
-
- 인지상태: {safe(client,'cognitive_status') or '기록 없음'}
|
| 788 |
-
- 이동상태: {safe(client,'mobility_status') or '기록 없음'}
|
| 789 |
-
- 식사상태: {safe(client,'diet_status') or '기록 없음'}
|
| 790 |
-
- 배변/배뇨상태: {safe(client,'toileting_status') or '기록 없음'}
|
| 791 |
-
|
| 792 |
-
[상담일지 연동 요약]
|
| 793 |
-
{counseling_summary}
|
| 794 |
-
|
| 795 |
-
[욕구사정 연동 요약]
|
| 796 |
-
{needs_summary}
|
| 797 |
-
|
| 798 |
-
[추가 상태변화]
|
| 799 |
-
{custom_status or '추가로 입력된 상태변화는 없으나, 기존 기록을 바탕으로 지속 관찰이 필요함.'}
|
| 800 |
-
|
| 801 |
-
회의 결과 {case_type}과 관련하여 {keywords} 항목을 중심으로 개입하기로 하였으며, {tone}
|
| 802 |
-
""".strip()
|
| 803 |
-
|
| 804 |
-
goal = custom_goal.strip() or details["goal"]
|
| 805 |
-
|
| 806 |
-
selected_methods = details["plan"][:4]
|
| 807 |
-
methods_str = "\n".join(f"- {method}" for method in selected_methods)
|
| 808 |
-
|
| 809 |
-
plan = f"""
|
| 810 |
-
[1차 사례관리 목표]
|
| 811 |
-
{goal}
|
| 812 |
-
|
| 813 |
-
[1차 사례관리 계획 및 구체적 지원방법]
|
| 814 |
-
{methods_str}
|
| 815 |
-
|
| 816 |
-
[외부자원 연계 방안]
|
| 817 |
-
- {details['resource']}
|
| 818 |
-
|
| 819 |
-
[급여제공계획 반영 여부 점검]
|
| 820 |
-
☑ 급여제공계획 변경 필요
|
| 821 |
-
☑ 욕구사정 재점검 필요
|
| 822 |
-
☑ 보호자 상담 필요
|
| 823 |
-
☑ 상태변화기록 연계 필요
|
| 824 |
-
""".strip()
|
| 825 |
-
|
| 826 |
-
role_division = build_role_text(case_type, custom_roles)
|
| 827 |
-
|
| 828 |
-
implementation = f"""
|
| 829 |
-
[역할분담에 따른 시행과정 및 구체적 지원방법 수행]
|
| 830 |
-
- 시설장: 사례관리에 따른 예산 편성 및 급여제공 계획 반영 프로세스가 적정하게 이루어지는지 검증함.
|
| 831 |
-
- 사회복지사: 보호자와 유선 및 방문상담을 통해 서비스 조정을 이행하였으며, 개별이용계획 지원방법에 맞춰 계획을 수립함.
|
| 832 |
-
- 요양보호사: 일상 돌봄 서비스 제공 중 상기 지원방법 지침을 이행하고, 수급자의 특이 반응을 일상기록지에 즉시 보고 및 작성함.
|
| 833 |
-
- 간호조무사: 기저귀 케어, 복약 체크, 식사/수분 섭취 비중을 점검하고, 보건소 및 방문간호 서비스 연계 필요성을 지속 판단함.
|
| 834 |
-
- 물리치료사: 실내 보행 상태와 어지럼 여부를 관찰하고, 보행보조기 정비 및 실내 동선 안전을 위해 자문함.
|
| 835 |
-
|
| 836 |
-
[과정 점검 결과]
|
| 837 |
-
- 계획 수립 이후 30일간 수급자 밀착 케어와 관찰이 이루어졌으며, 보호자의 피드백을 수렴하여 개선안을 시행함.
|
| 838 |
-
""".strip()
|
| 839 |
-
|
| 840 |
-
second_result = f"""
|
| 841 |
-
[2차 결과회의 내용]
|
| 842 |
-
- 1차 계획 수립 이후 30일간의 개별이용계획 지원사항 및 실행과정을 검증함.
|
| 843 |
-
|
| 844 |
-
[시행과정 점검]
|
| 845 |
-
- 요양보호사 및 간호조무사의 일상 및 건강 관찰기록을 검토하였으며, 보호자 면담 결과를 통합함.
|
| 846 |
-
|
| 847 |
-
[목표달성 여부 평가]
|
| 848 |
-
- 평가 결과: 부분달성 및 지속 관찰 필요
|
| 849 |
-
- 미달성 사유: 수급자의 인지 노화 진행 속도 및 신체 강직으로 인해 보행 자립도가 완전히 개선되지는 못함.
|
| 850 |
-
- 후속계획: 외부자원({details['resource']}) 연계를 강화하고, 급여제공계획을 재조정하여 안전 동행을 지속함.
|
| 851 |
-
|
| 852 |
-
[급여제공 반영 결과]
|
| 853 |
-
- 수급자의 개별 지원 행동지침이 급여제공기록지 및 급여제공계획서에 정합성 있게 작성 완료되었음을 확인함.
|
| 854 |
-
""".strip()
|
| 855 |
-
|
| 856 |
-
return selection, first_content, goal, plan, role_division, implementation, second_result
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
def evaluate_case(selection, first_content, plan, role_division, implementation, second_result, counseling_summary, needs_summary):
|
| 861 |
-
required = {
|
| 862 |
-
"선정사유": bool(selection.strip()),
|
| 863 |
-
"상담일지 연동": "상담" in counseling_summary and "저장된 상담일지 없어" not in counseling_summary,
|
| 864 |
-
"욕구사정 연동": bool(needs_summary.strip()),
|
| 865 |
-
"1차 계획": bool(plan.strip()) and "목표" in plan,
|
| 866 |
-
"역할분담": all(word in role_division for word in ["시설장", "사회복지사", "요양보호사", "간호조무사", "물리치료사"]),
|
| 867 |
-
"시행과정": bool(implementation.strip()) and "시행과정" in implementation,
|
| 868 |
-
"2차 결과회의": bool(second_result.strip()) and "결과" in second_result,
|
| 869 |
-
"보호자 의견/상태변화": ("보호자" in first_content or "보호자" in second_result) and ("상태변화" in first_content or "변화" in second_result),
|
| 870 |
-
"급여제공 반영": "급여제공" in plan and "급여제공" in second_result,
|
| 871 |
-
}
|
| 872 |
-
score = int(sum(required.values()) / len(required) * 100)
|
| 873 |
-
missing = [k for k, v in required.items() if not v]
|
| 874 |
-
if score >= 90:
|
| 875 |
-
result = "평가 적합도가 높습니다. 사례선정, 1차 계획, 역할분담, 시행과정, 2차 결과평가가 연결되어 있습니다."
|
| 876 |
-
elif score >= 75:
|
| 877 |
-
result = "대체로 적합하나 일부 보완이 필요합니다. 부족 항목을 추가하면 평가 대응력이 높아집니다."
|
| 878 |
-
else:
|
| 879 |
-
result = "보완이 필요합니다. 상담일지, 욕구사정, 역할별 시행과정, 2차 결과평가가 더 구체적으로 연결되어야 합니다."
|
| 880 |
-
return score, missing, result
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
# -----------------------------
|
| 884 |
-
# 엑셀 함수 (선 잘림 문제 및 색상 개선 적용)
|
| 885 |
-
# -----------------------------
|
| 886 |
-
def set_page_style(ws):
|
| 887 |
-
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
| 888 |
-
ws.page_setup.orientation = "portrait"
|
| 889 |
-
ws.page_setup.fitToWidth = 1
|
| 890 |
-
ws.page_setup.fitToHeight = 0
|
| 891 |
-
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
| 892 |
-
ws.page_margins.left = 0.3
|
| 893 |
-
ws.page_margins.right = 0.3
|
| 894 |
-
ws.page_margins.top = 0.4
|
| 895 |
-
ws.page_margins.bottom = 0.4
|
| 896 |
-
ws.sheet_view.showGridLines = False
|
| 897 |
-
|
| 898 |
-
def style_range(ws, cell_range, border_on=True, fill=None, font=None, alignment=None):
|
| 899 |
-
"""병합 셀 포함 범위 전체에 스타일 적용 (검정색 테두리로 가시성 확보)"""
|
| 900 |
-
# 선 색상을 선명한 검정(000000)으로 변경하여 렌더링 누락 방지
|
| 901 |
-
thin = Side(style="thin", color="000000")
|
| 902 |
-
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 903 |
-
|
| 904 |
-
cells = ws[cell_range]
|
| 905 |
-
if not isinstance(cells, tuple):
|
| 906 |
-
cells = ((cells,),)
|
| 907 |
-
|
| 908 |
-
for row in cells:
|
| 909 |
-
for cell in row:
|
| 910 |
-
if border_on:
|
| 911 |
-
cell.border = border
|
| 912 |
-
if fill:
|
| 913 |
-
cell.fill = fill
|
| 914 |
-
if font:
|
| 915 |
-
cell.font = font
|
| 916 |
-
if alignment:
|
| 917 |
-
cell.alignment = alignment
|
| 918 |
-
|
| 919 |
-
def write_title_with_approval(ws, title, title_fill, header_fill):
|
| 920 |
-
for col in range(1, 10):
|
| 921 |
-
ws.column_dimensions[get_column_letter(col)].width = 13
|
| 922 |
-
|
| 923 |
-
ws.merge_cells("A1:G2")
|
| 924 |
-
c = ws["A1"]
|
| 925 |
-
c.value = title
|
| 926 |
-
c.font = Font(name="Malgun Gothic", size=24, bold=True)
|
| 927 |
-
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 928 |
-
style_range(ws, "A1:G2", fill=title_fill)
|
| 929 |
-
|
| 930 |
-
headers = ["담당자", "시설장"]
|
| 931 |
-
for idx, col in enumerate(range(8, 10)):
|
| 932 |
-
c1 = ws.cell(1, col)
|
| 933 |
-
c2 = ws.cell(2, col)
|
| 934 |
-
c1.value = headers[idx]
|
| 935 |
-
c2.value = ""
|
| 936 |
-
c1.font = Font(name="Malgun Gothic", size=12, bold=True)
|
| 937 |
-
c2.font = Font(name="Malgun Gothic", size=11)
|
| 938 |
-
c1.alignment = Alignment(horizontal="center", vertical="center")
|
| 939 |
-
c2.alignment = Alignment(horizontal="center", vertical="center")
|
| 940 |
-
c1.fill = header_fill
|
| 941 |
-
style_range(ws, f"{get_column_letter(col)}1:{get_column_letter(col)}2")
|
| 942 |
-
|
| 943 |
-
ws.row_dimensions[1].height = 28
|
| 944 |
-
ws.row_dimensions[2].height = 42
|
| 945 |
-
|
| 946 |
-
def write_info_row(ws, row, a, b, c, d, e, f, header_fill):
|
| 947 |
-
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=3)
|
| 948 |
-
ws.merge_cells(start_row=row, start_column=5, end_row=row, end_column=6)
|
| 949 |
-
ws.merge_cells(start_row=row, start_column=8, end_row=row, end_column=9)
|
| 950 |
-
|
| 951 |
-
pairs = [(1, a), (2, b), (4, c), (5, d), (7, e), (8, f)]
|
| 952 |
-
for col, val in pairs:
|
| 953 |
-
is_label = col in [1, 4, 7]
|
| 954 |
-
cell = ws.cell(row, col)
|
| 955 |
-
cell.value = val
|
| 956 |
-
cell.font = Font(name="Malgun Gothic", size=11, bold=is_label)
|
| 957 |
-
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 958 |
-
if is_label:
|
| 959 |
-
cell.fill = header_fill
|
| 960 |
-
|
| 961 |
-
style_range(ws, f"A{row}:I{row}")
|
| 962 |
-
ws.row_dimensions[row].height = 30
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
def split_text_by_length(text, max_len=650):
|
| 966 |
-
text = str(text or "").strip()
|
| 967 |
-
if not text:
|
| 968 |
-
return [""]
|
| 969 |
-
chunks = []
|
| 970 |
-
while len(text) > max_len:
|
| 971 |
-
cut = text.rfind("\n", 0, max_len)
|
| 972 |
-
if cut == -1:
|
| 973 |
-
cut = text.rfind(". ", 0, max_len)
|
| 974 |
-
if cut == -1:
|
| 975 |
-
cut = text.rfind("다.", 0, max_len)
|
| 976 |
-
if cut != -1:
|
| 977 |
-
cut += 2
|
| 978 |
-
if cut == -1 or cut < int(max_len * 0.45):
|
| 979 |
-
cut = max_len
|
| 980 |
-
chunks.append(text[:cut].strip())
|
| 981 |
-
text = text[cut:].strip()
|
| 982 |
-
if text:
|
| 983 |
-
chunks.append(text)
|
| 984 |
-
return chunks or [""]
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
def write_section(ws, row, title, content, header_fill, min_height=90):
|
| 988 |
-
pages = split_text_by_length(content, 650)
|
| 989 |
-
for page_idx, page_text in enumerate(pages, start=1):
|
| 990 |
-
display_title = f"{title} ({page_idx}/{len(pages)}페이지)" if len(pages) > 1 else title
|
| 991 |
-
|
| 992 |
-
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
|
| 993 |
-
cell = ws.cell(row, 1)
|
| 994 |
-
cell.value = display_title
|
| 995 |
-
cell.font = Font(name="Malgun Gothic", size=15, bold=True)
|
| 996 |
-
cell.alignment = Alignment(horizontal="center", vertical="center")
|
| 997 |
-
cell.fill = header_fill
|
| 998 |
-
style_range(ws, f"A{row}:I{row}")
|
| 999 |
-
ws.row_dimensions[row].height = 30
|
| 1000 |
-
row += 1
|
| 1001 |
-
|
| 1002 |
-
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
|
| 1003 |
-
cell2 = ws.cell(row, 1)
|
| 1004 |
-
cell2.value = page_text
|
| 1005 |
-
cell2.font = Font(name="Malgun Gothic", size=11)
|
| 1006 |
-
cell2.alignment = Alignment(horizontal="left", vertical="top", wrap_text=True)
|
| 1007 |
-
style_range(ws, f"A{row}:I{row}")
|
| 1008 |
-
|
| 1009 |
-
lines = sum((len(line) // 40) + 1 for line in str(page_text).split("\n"))
|
| 1010 |
-
calculated_height = min(390, lines * 24 + 15)
|
| 1011 |
-
ws.row_dimensions[row].height = max(min_height, calculated_height)
|
| 1012 |
-
if page_idx < len(pages):
|
| 1013 |
-
ws.row_breaks.append(Break(id=row))
|
| 1014 |
-
row += 1
|
| 1015 |
-
|
| 1016 |
-
return row
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
def generate_excel(data):
|
| 1020 |
-
wb = Workbook()
|
| 1021 |
-
title_fill = PatternFill("solid", fgColor="EDE9FE")
|
| 1022 |
-
header_fill = PatternFill("solid", fgColor="F3F4F6")
|
| 1023 |
-
|
| 1024 |
-
# 1차 계획회의록 시트
|
| 1025 |
-
ws1 = wb.active
|
| 1026 |
-
ws1.title = "1차계획회의록"
|
| 1027 |
-
set_page_style(ws1)
|
| 1028 |
-
write_title_with_approval(ws1, "사례관리 1차 계획회의록", title_fill, header_fill)
|
| 1029 |
-
|
| 1030 |
-
r = 3
|
| 1031 |
-
write_info_row(ws1, r, "기관명", data["institution_name"], "기관유형", data["institution_type"], "회의일자", data["first_meeting_date"], header_fill); r += 1
|
| 1032 |
-
write_info_row(ws1, r, "수급자", data["client_masked_name"], "장기요양등급", data["grade"], "사례유형", data["case_type"], header_fill); r += 1
|
| 1033 |
-
write_info_row(ws1, r, "인정번호", data.get("recognition_number", ""), "인정기간", f"{data.get('recognition_start_date','')} ~ {data.get('recognition_end_date','')}", "기한알림", data.get("recognition_alert", ""), header_fill); r += 1
|
| 1034 |
-
write_info_row(ws1, r, "회의장소", data["meeting_place"], "작성자", data["writer"], "2차예정일", data["second_meeting_date"], header_fill); r += 1
|
| 1035 |
-
|
| 1036 |
-
r = write_section(ws1, r, "선정사유", data["selection_reason"], header_fill, 80)
|
| 1037 |
-
r = write_section(ws1, r, "상담일지 연동 요약", data["counseling_summary"], header_fill, 90)
|
| 1038 |
-
r = write_section(ws1, r, "욕구사정 연동 요약", data["needs_summary"], header_fill, 90)
|
| 1039 |
-
r = write_section(ws1, r, "1차 회의내용", data["first_content"], header_fill, 150)
|
| 1040 |
-
r = write_section(ws1, r, "1차 사례관리 목표 및 계획", f"[목표]\n{data['goal']}\n\n[계획]\n{data['first_plan']}", header_fill, 140)
|
| 1041 |
-
r = write_section(ws1, r, "역할분담", data["role_division"], header_fill, 130)
|
| 1042 |
-
r = write_section(ws1, r, "참석자 명단", data.get("attendees_text", "시설장, 사회복지사, 요양보호사, 간호조무사 참석"), header_fill, 90)
|
| 1043 |
-
r = write_section(ws1, r, "평가 적합도 점검", f"{data['evaluation_score']}점\n부족 항목: {data['missing_items']}\n{data['compliance_result']}", header_fill, 80)
|
| 1044 |
-
|
| 1045 |
-
# 사진첨부
|
| 1046 |
-
if data.get("photo_paths"):
|
| 1047 |
-
ws1.merge_cells(start_row=r, start_column=1, end_row=r, end_column=9)
|
| 1048 |
-
ws1.cell(r, 1).value = "사진첨부"
|
| 1049 |
-
ws1.cell(r, 1).font = Font(name="Malgun Gothic", size=15, bold=True)
|
| 1050 |
-
ws1.cell(r, 1).alignment = Alignment(horizontal="center", vertical="center")
|
| 1051 |
-
ws1.cell(r, 1).fill = header_fill
|
| 1052 |
-
r += 1
|
| 1053 |
-
|
| 1054 |
-
anchors = ["A", "D", "G"]
|
| 1055 |
-
img_row = r
|
| 1056 |
-
for idx, photo_path in enumerate(data.get("photo_paths", [])[:3]):
|
| 1057 |
-
try:
|
| 1058 |
-
img = XLImage(photo_path)
|
| 1059 |
-
img.width = 210
|
| 1060 |
-
img.height = 150
|
| 1061 |
-
ws1.add_image(img, f"{anchors[idx]}{img_row}")
|
| 1062 |
-
except Exception:
|
| 1063 |
-
pass
|
| 1064 |
-
|
| 1065 |
-
for rr in range(img_row, img_row + 8):
|
| 1066 |
-
ws1.row_dimensions[rr].height = 22
|
| 1067 |
-
r = img_row + 8
|
| 1068 |
-
|
| 1069 |
-
# 공통 안내문구 추가
|
| 1070 |
-
ws1.merge_cells(start_row=r, start_column=1, end_row=r, end_column=9)
|
| 1071 |
-
ws1.cell(r, 1).value = "※ 생성된 문서는 그대로 사용하셔도 되며, 기관의 운영방침, 수급자 상태, 보호자 의견 및 평가기준에 따라 추가 보완사항은 얼마든지 수정 가능합니다. 기관의 상황에 맞게 활용하시기 바랍니다."
|
| 1072 |
-
ws1.cell(r, 1).font = Font(name="Malgun Gothic", size=8.5, color="595959", italic=True)
|
| 1073 |
-
ws1.cell(r, 1).alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
| 1074 |
-
style_range(ws1, f"A{r}:I{r}")
|
| 1075 |
-
ws1.row_dimensions[r].height = 36
|
| 1076 |
-
r += 1
|
| 1077 |
-
|
| 1078 |
-
# 테두리 스타일 일괄 적용
|
| 1079 |
-
thin = Side(style="thin", color="000000")
|
| 1080 |
-
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 1081 |
-
for row in range(1, r):
|
| 1082 |
-
for col in range(1, 10):
|
| 1083 |
-
cell = ws1.cell(row, col)
|
| 1084 |
-
cell.border = border
|
| 1085 |
-
if not cell.font.name:
|
| 1086 |
-
cell.font = Font(name="Malgun Gothic", size=11)
|
| 1087 |
-
ws1.print_area = f"A1:I{r - 1}"
|
| 1088 |
-
|
| 1089 |
-
# 2차 결과회의록 시트 생성
|
| 1090 |
-
ws2 = wb.create_sheet("2차결과회의록")
|
| 1091 |
-
set_page_style(ws2)
|
| 1092 |
-
write_title_with_approval(ws2, "사례관리 2차 결과회의록", title_fill, header_fill)
|
| 1093 |
-
|
| 1094 |
-
r2 = 3
|
| 1095 |
-
write_info_row(ws2, r2, "기관명", data["institution_name"], "기관유형", data["institution_type"], "회의일자", data["second_meeting_date"], header_fill); r2 += 1
|
| 1096 |
-
write_info_row(ws2, r2, "수급자", data["client_masked_name"], "장기요양등급", data["grade"], "사례유형", data["case_type"], header_fill); r2 += 1
|
| 1097 |
-
write_info_row(ws2, r2, "인정번호", data.get("recognition_number", ""), "인정기간", f"{data.get('recognition_start_date','')} ~ {data.get('recognition_end_date','')}", "기한알림", data.get("recognition_alert", ""), header_fill); r2 += 1
|
| 1098 |
-
write_info_row(ws2, r2, "회의장소", data["meeting_place"], "작성자", data["writer"], "1차회의일", data["first_meeting_date"], header_fill); r2 += 1
|
| 1099 |
-
|
| 1100 |
-
r2 = write_section(ws2, r2, "선정사유", data["selection_reason"], header_fill, 80)
|
| 1101 |
-
r2 = write_section(ws2, r2, "1차 사례관리 목표 및 계획", f"[목표]\n{data['goal']}\n\n[계획]\n{data['first_plan']}", header_fill, 130)
|
| 1102 |
-
r2 = write_section(ws2, r2, "역할별 시행과정", data["implementation_process"], header_fill, 150)
|
| 1103 |
-
r2 = write_section(ws2, r2, "2차 회의결과 및 평가", data["second_result"], header_fill, 150)
|
| 1104 |
-
r2 = write_section(ws2, r2, "참석자 명단", data.get("attendees_text", "시설장, 사회복지사, 요양보호사, 간호조무사 참석"), header_fill, 90)
|
| 1105 |
-
|
| 1106 |
-
# 공통 안내문구 추가
|
| 1107 |
-
ws2.merge_cells(start_row=r2, start_column=1, end_row=r2, end_column=9)
|
| 1108 |
-
ws2.cell(r2, 1).value = "※ 생성된 문서는 그대로 사용하셔도 되며, 기관의 운영방침, 수급자 상태, 보호자 의견 및 평가기준에 따라 추가 보완사항은 얼마든지 수정 가능합니다. 기관의 상황에 맞게 활용하시기 바랍니다."
|
| 1109 |
-
ws2.cell(r2, 1).font = Font(name="Malgun Gothic", size=8.5, color="595959", italic=True)
|
| 1110 |
-
ws2.cell(r2, 1).alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
| 1111 |
-
style_range(ws2, f"A{r2}:I{r2}")
|
| 1112 |
-
ws2.row_dimensions[r2].height = 36
|
| 1113 |
-
r2 += 1
|
| 1114 |
-
|
| 1115 |
-
for row in range(1, r2):
|
| 1116 |
-
for col in range(1, 10):
|
| 1117 |
-
cell = ws2.cell(row, col)
|
| 1118 |
-
cell.border = border
|
| 1119 |
-
if not cell.font.name:
|
| 1120 |
-
cell.font = Font(name="Malgun Gothic", size=11)
|
| 1121 |
-
ws2.print_area = f"A1:I{r2 - 1}"
|
| 1122 |
-
|
| 1123 |
-
output = BytesIO()
|
| 1124 |
-
wb.save(output)
|
| 1125 |
-
output.seek(0)
|
| 1126 |
-
return output
|
| 1127 |
-
|
| 1128 |
-
|
| 1129 |
-
def save_uploaded_photos(uploaded_files):
|
| 1130 |
-
paths = []
|
| 1131 |
-
for file in (uploaded_files or []):
|
| 1132 |
-
suffix = os.path.splitext(file.name)[1].lower() or ".png"
|
| 1133 |
-
temp_path = os.path.join(tempfile.gettempdir(), f"case_photo_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{suffix}")
|
| 1134 |
-
with open(temp_path, "wb") as f:
|
| 1135 |
-
f.write(file.getbuffer())
|
| 1136 |
-
paths.append(temp_path)
|
| 1137 |
-
return paths
|
| 1138 |
-
|
| 1139 |
-
|
| 1140 |
-
def get_client_history(db_path: str, client_id: int):
|
| 1141 |
-
conn = sqlite3.connect(db_path)
|
| 1142 |
-
try:
|
| 1143 |
-
counsel_df = pd.read_sql_query(
|
| 1144 |
-
"SELECT counseling_date, counseling_type, counseling_reason, client_status_change, guardian_opinion FROM counseling_records WHERE client_id = ? ORDER BY counseling_date DESC, id DESC LIMIT 5",
|
| 1145 |
-
conn, params=(int(client_id),)
|
| 1146 |
-
)
|
| 1147 |
-
except Exception:
|
| 1148 |
-
counsel_df = pd.DataFrame()
|
| 1149 |
-
try:
|
| 1150 |
-
status_df = pd.read_sql_query(
|
| 1151 |
-
"SELECT record_date, change_category, body_status, cognitive_status, staff_observation, guardian_opinion FROM status_change_records WHERE client_id = ? ORDER BY record_date DESC, id DESC LIMIT 5",
|
| 1152 |
-
conn, params=(int(client_id),)
|
| 1153 |
-
)
|
| 1154 |
-
except Exception:
|
| 1155 |
-
status_df = pd.DataFrame()
|
| 1156 |
-
conn.close()
|
| 1157 |
-
return counsel_df, status_df
|
| 1158 |
-
|
| 1159 |
-
|
| 1160 |
-
# -----------------------------
|
| 1161 |
-
# Streamlit 화면 구성 (모듈 레벨 실행)
|
| 1162 |
-
# -----------------------------
|
| 1163 |
-
menu = st.sidebar.radio("메뉴", ["사례관리 생성", "저장기록 보기"])
|
| 1164 |
-
|
| 1165 |
-
st.sidebar.success("DB 연결")
|
| 1166 |
-
st.sidebar.caption(DB_PATH)
|
| 1167 |
-
|
| 1168 |
-
clients_df = load_clients()
|
| 1169 |
-
|
| 1170 |
-
if menu == "저장기록 보기":
|
| 1171 |
-
st.subheader("📚 저장된 사례관리 기록")
|
| 1172 |
-
conn = get_conn()
|
| 1173 |
-
try:
|
| 1174 |
-
records_df = pd.read_sql_query("SELECT * FROM case_management_records ORDER BY id DESC LIMIT 20", conn)
|
| 1175 |
-
if records_df.empty:
|
| 1176 |
-
st.info("저장된 사례관리 기록이 없습니다.")
|
| 1177 |
-
else:
|
| 1178 |
-
st.dataframe(records_df, use_container_width=True)
|
| 1179 |
-
except Exception as e:
|
| 1180 |
-
st.error(f"기록 조회 중 오류가 발생했습니다: {e}")
|
| 1181 |
-
conn.close()
|
| 1182 |
-
|
| 1183 |
-
elif menu == "사례관리 생성":
|
| 1184 |
-
mode_options = []
|
| 1185 |
-
if not clients_df.empty:
|
| 1186 |
-
mode_options.append("수급자 선택")
|
| 1187 |
-
mode_options.append("직접입력")
|
| 1188 |
-
|
| 1189 |
-
input_mode = st.radio("수급자 입력 방식", mode_options, horizontal=True)
|
| 1190 |
-
|
| 1191 |
-
if input_mode == "수급자 선택":
|
| 1192 |
-
options = clients_df.apply(
|
| 1193 |
-
lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_type']} / {x.get('status','')}",
|
| 1194 |
-
axis=1
|
| 1195 |
-
).tolist()
|
| 1196 |
-
|
| 1197 |
-
selected_option = st.selectbox("수급자 선택", options)
|
| 1198 |
-
selected_id = int(selected_option.split("번")[0])
|
| 1199 |
-
client = clients_df[clients_df["id"] == selected_id].iloc[0]
|
| 1200 |
-
|
| 1201 |
-
client_id = int(safe(client, "id", 0) or 0)
|
| 1202 |
-
institution_type = safe(client, "institution_type", "방문요양")
|
| 1203 |
-
institution_name = safe(client, "institution_name", "BeeCare 장기요양기관")
|
| 1204 |
-
else:
|
| 1205 |
-
st.info("💡 직접입력 모드입니다. 아래에 테스트할 수급자 정보를 직접 입력해 주세요.")
|
| 1206 |
-
c1, c2, c3 = st.columns(3)
|
| 1207 |
-
temp_name = c1.text_input("수급자 이름", "홍길동")
|
| 1208 |
-
temp_grade = c2.selectbox("장기요양등급", ["1등급", "2등급", "3등급", "4등급", "5등급", "인지지원등급", "등급외"], index=2)
|
| 1209 |
-
temp_inst_type = c3.selectbox("기관 유형", ["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"], index=0)
|
| 1210 |
-
|
| 1211 |
-
c4, c5, c6 = st.columns(3)
|
| 1212 |
-
temp_inst_name = c4.text_input("기관명", "행복 장기요양기관")
|
| 1213 |
-
temp_rec_no = c5.text_input("인정번호", "L1234567890")
|
| 1214 |
-
temp_status = c6.selectbox("상태", ["이용중", "입소중", "퇴소", "중지", "사망"], index=0)
|
| 1215 |
-
|
| 1216 |
-
c7, c8 = st.columns(2)
|
| 1217 |
-
temp_rec_start = c7.date_input("인정기간 시작일", value=date.today() - timedelta(days=365))
|
| 1218 |
-
temp_rec_end = c8.date_input("인정기간 종료일", value=date.today() + timedelta(days=365))
|
| 1219 |
-
|
| 1220 |
-
st.markdown("### 건강 및 생활 상태 직접 입력")
|
| 1221 |
-
c9, c10 = st.columns(2)
|
| 1222 |
-
temp_condition = c9.text_area("주요 질환 / 상태", "치매, 고혈압, 당뇨, 낙상위험 높음")
|
| 1223 |
-
temp_cognitive = c10.text_area("인지 상태", "단기기억 저하, 배회 증상 있음")
|
| 1224 |
-
|
| 1225 |
-
c11, c12 = st.columns(2)
|
| 1226 |
-
temp_mobility = c11.text_area("이동 상태", "보행보조기 사용, 이동 시 부축 필요")
|
| 1227 |
-
temp_toileting = c12.text_area("배변 / 배뇨 상태", "화장실 유도 필요")
|
| 1228 |
-
|
| 1229 |
-
client = pd.Series({
|
| 1230 |
-
"id": 0,
|
| 1231 |
-
"name": temp_name,
|
| 1232 |
-
"masked_name": mask_name(temp_name),
|
| 1233 |
-
"care_grade": temp_grade,
|
| 1234 |
-
"institution_type": temp_inst_type,
|
| 1235 |
-
"institution_name": temp_inst_name,
|
| 1236 |
-
"recognition_number": temp_rec_no,
|
| 1237 |
-
"recognition_start_date": str(temp_rec_start),
|
| 1238 |
-
"recognition_end_date": str(temp_rec_end),
|
| 1239 |
-
"main_condition": temp_condition,
|
| 1240 |
-
"cognitive_status": temp_cognitive,
|
| 1241 |
-
"mobility_status": temp_mobility,
|
| 1242 |
-
"diet_status": "일반식",
|
| 1243 |
-
"toileting_status": temp_toileting,
|
| 1244 |
-
"status": temp_status
|
| 1245 |
-
})
|
| 1246 |
-
client_id = 0
|
| 1247 |
-
institution_type = temp_inst_type
|
| 1248 |
-
institution_name = temp_inst_name
|
| 1249 |
-
|
| 1250 |
-
m1, m2, m3, m4 = st.columns(4)
|
| 1251 |
-
m1.metric("수급자", safe(client, "masked_name"))
|
| 1252 |
-
m2.metric("등급", safe(client, "care_grade"))
|
| 1253 |
-
m3.metric("기관유형", institution_type)
|
| 1254 |
-
m4.metric("인정기간 알림", recognition_alert_text(safe(client, "recognition_end_date")))
|
| 1255 |
-
|
| 1256 |
-
# RAG 데이터 연동 조회 및 사례유형 추천을 먼저 수행
|
| 1257 |
-
counseling_df, _ = get_client_history(DB_PATH, client_id)
|
| 1258 |
-
counseling_summary = summarize_counseling(counseling_df)
|
| 1259 |
-
|
| 1260 |
-
needs_df = load_needs_assessment(client_id)
|
| 1261 |
-
needs_summary = summarize_needs(needs_df, client, "")
|
| 1262 |
-
|
| 1263 |
-
recommended_type = recommend_case_type(counseling_summary, needs_summary, safe(client, "main_condition"))
|
| 1264 |
-
|
| 1265 |
-
with st.expander("📌 인정정보 확인", expanded=False):
|
| 1266 |
-
st.write(f"인정번호: {safe(client, 'recognition_number') or '미입력'}")
|
| 1267 |
-
st.write(f"인정기간: {safe(client, 'recognition_start_date') or '미입력'} ~ {safe(client, 'recognition_end_date') or '미입력'}")
|
| 1268 |
-
st.info(recognition_alert_text(safe(client, 'recognition_end_date')))
|
| 1269 |
-
|
| 1270 |
-
st.markdown("### 회의 기본정보")
|
| 1271 |
-
col1, col2, col3 = st.columns(3)
|
| 1272 |
-
|
| 1273 |
-
case_types_list = list(CASE_TYPES.keys())
|
| 1274 |
-
try:
|
| 1275 |
-
rec_index = case_types_list.index(recommended_type)
|
| 1276 |
-
except ValueError:
|
| 1277 |
-
rec_index = 0
|
| 1278 |
-
|
| 1279 |
-
case_type = col1.selectbox("사례유형", case_types_list, index=rec_index)
|
| 1280 |
-
col1.info(f"💡 시스템 추천 사례유형: **{recommended_type}**")
|
| 1281 |
-
|
| 1282 |
-
first_meeting_date = col2.date_input("1차 회의일자", value=date.today())
|
| 1283 |
-
second_meeting_date = col3.date_input("2차 결과회의일자 (보통 30일 후)", value=date.today() + timedelta(days=30))
|
| 1284 |
-
|
| 1285 |
-
col4, col5 = st.columns(2)
|
| 1286 |
-
meeting_place = col4.text_input("회의장소", "기관 사무실 및 회의실")
|
| 1287 |
-
writer = col5.text_input("작성자", "사회복지사")
|
| 1288 |
-
|
| 1289 |
-
st.markdown("### 참석자")
|
| 1290 |
-
c1, c2, c3, c4 = st.columns(4)
|
| 1291 |
-
director_attendee = c1.text_input("시설장", "시설장")
|
| 1292 |
-
sw_attendee = c2.text_input("사회복지사", "사회복지사")
|
| 1293 |
-
cg_attendee = c3.text_input("요양보호사", "요양보호사")
|
| 1294 |
-
nurse_attendee = c4.text_input("간호(조무)사", "간호조무사")
|
| 1295 |
-
|
| 1296 |
-
c5, c6 = st.columns(2)
|
| 1297 |
-
therapist_attendee = c5.text_input("물리/작업치료사 (선택)", "")
|
| 1298 |
-
guardian_attendee = c6.text_input("보호자 (선택)", "")
|
| 1299 |
-
extra_attendees = st.text_input("기타 참석자 (선택)", "")
|
| 1300 |
-
|
| 1301 |
-
attendees_text = build_attendees_text(
|
| 1302 |
-
director_attendee, sw_attendee, cg_attendee, nurse_attendee,
|
| 1303 |
-
therapist_attendee, guardian_attendee, extra_attendees
|
| 1304 |
-
)
|
| 1305 |
-
|
| 1306 |
-
st.markdown("### 수동 추가/조정 입력 (선택사항)")
|
| 1307 |
-
custom_selection = st.text_area("선정사유 수동 입력", placeholder="비워둘 시 자동으로 작성합니다.", height=70)
|
| 1308 |
-
custom_status = st.text_area("추가 상태변화 기록", placeholder="비워둘 시 기본 상태를 토대로 작성합니다.", height=70)
|
| 1309 |
-
custom_goal = st.text_area("1차 사례관리 목표 수동 입력", placeholder="비워둘 시 기본 목표를 작성합니다.", height=70)
|
| 1310 |
-
custom_roles = st.text_area("역할분담 수동 입력", placeholder="비워둘 시 기본 직종별 역할분담을 작성합니다.", height=70)
|
| 1311 |
-
|
| 1312 |
-
photos = st.file_uploader("사진첨부 (최대 3장, 선택사항)", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
|
| 1313 |
-
|
| 1314 |
-
if st.button("📝 사례관리 통합 회의록 생성", use_container_width=True):
|
| 1315 |
-
selection, first_content, goal, plan, role_division, implementation, second_result = build_case_documents(
|
| 1316 |
-
client, counseling_summary, needs_summary, case_type,
|
| 1317 |
-
custom_selection, custom_status, custom_goal, custom_roles
|
| 1318 |
-
)
|
| 1319 |
-
|
| 1320 |
-
score, missing, compliance = evaluate_case(
|
| 1321 |
-
selection, first_content, plan, role_division, implementation, second_result,
|
| 1322 |
-
counseling_summary, needs_summary
|
| 1323 |
-
)
|
| 1324 |
-
|
| 1325 |
-
photo_paths = save_uploaded_photos(photos)
|
| 1326 |
-
|
| 1327 |
-
st.session_state["case_data"] = {
|
| 1328 |
-
"client_id": client_id,
|
| 1329 |
-
"client_masked_name": safe(client, "masked_name"),
|
| 1330 |
-
"institution_name": institution_name,
|
| 1331 |
-
"institution_type": institution_type,
|
| 1332 |
-
"grade": safe(client, "care_grade"),
|
| 1333 |
-
"recognition_number": safe(client, "recognition_number"),
|
| 1334 |
-
"recognition_start_date": safe(client, "recognition_start_date"),
|
| 1335 |
-
"recognition_end_date": safe(client, "recognition_end_date"),
|
| 1336 |
-
"recognition_alert": recognition_alert_text(safe(client, "recognition_end_date")),
|
| 1337 |
-
"case_type": case_type,
|
| 1338 |
-
"first_meeting_date": str(first_meeting_date),
|
| 1339 |
-
"second_meeting_date": str(second_meeting_date),
|
| 1340 |
-
"meeting_place": meeting_place,
|
| 1341 |
-
"writer": writer,
|
| 1342 |
-
"attendees_text": attendees_text,
|
| 1343 |
-
"selection_reason": selection,
|
| 1344 |
-
"first_content": first_content,
|
| 1345 |
-
"goal": goal,
|
| 1346 |
-
"first_plan": plan,
|
| 1347 |
-
"role_division": role_division,
|
| 1348 |
-
"implementation_process": implementation,
|
| 1349 |
-
"second_result": second_result,
|
| 1350 |
-
"counseling_summary": counseling_summary,
|
| 1351 |
-
"needs_summary": needs_summary,
|
| 1352 |
-
"evaluation_score": score,
|
| 1353 |
-
"missing_items": ", ".join(missing) if missing else "부족 항목 없음",
|
| 1354 |
-
"compliance_result": compliance,
|
| 1355 |
-
"photo_paths": photo_paths
|
| 1356 |
-
}
|
| 1357 |
-
|
| 1358 |
-
if "case_data" in st.session_state:
|
| 1359 |
-
data = st.session_state["case_data"]
|
| 1360 |
-
|
| 1361 |
-
st.markdown("---")
|
| 1362 |
-
st.subheader("생성된 사례관리 회의록 (수정 가능)")
|
| 1363 |
-
|
| 1364 |
-
data["selection_reason"] = st.text_area("선정사유", value=data["selection_reason"], height=100)
|
| 1365 |
-
data["first_content"] = st.text_area("1차 회의내용", value=data["first_content"], height=200)
|
| 1366 |
-
data["goal"] = st.text_area("목표", value=data["goal"], height=80)
|
| 1367 |
-
data["first_plan"] = st.text_area("1차 계획", value=data["first_plan"], height=150)
|
| 1368 |
-
data["role_division"] = st.text_area("역할분담", value=data["role_division"], height=150)
|
| 1369 |
-
data["implementation_process"] = st.text_area("시행과정", value=data["implementation_process"], height=150)
|
| 1370 |
-
data["second_result"] = st.text_area("2차 결과평가", value=data["second_result"], height=200)
|
| 1371 |
-
|
| 1372 |
-
# 평가적합도 재조정
|
| 1373 |
-
score, missing, compliance = evaluate_case(
|
| 1374 |
-
data["selection_reason"], data["first_content"], data["first_plan"],
|
| 1375 |
-
data["role_division"], data["implementation_process"], data["second_result"],
|
| 1376 |
-
data["counseling_summary"], data["needs_summary"]
|
| 1377 |
-
)
|
| 1378 |
-
data["evaluation_score"] = score
|
| 1379 |
-
data["missing_items"] = ", ".join(missing) if missing else "부족 항목 없음"
|
| 1380 |
-
data["compliance_result"] = compliance
|
| 1381 |
-
|
| 1382 |
-
st.subheader("평가 적합도 점검")
|
| 1383 |
-
e1, e2 = st.columns(2)
|
| 1384 |
-
e1.metric("평가 적합도", f"{score}점")
|
| 1385 |
-
e2.metric("부족 항목", data["missing_items"])
|
| 1386 |
-
|
| 1387 |
-
if score >= 90:
|
| 1388 |
-
st.success(compliance)
|
| 1389 |
-
else:
|
| 1390 |
-
st.warning(compliance)
|
| 1391 |
-
|
| 1392 |
-
if st.button("💾 사례관리 기록 DB 저장", use_container_width=True):
|
| 1393 |
-
save_case_record(data)
|
| 1394 |
-
st.success("사례관리 기록이 DB에 성공적으로 저장되었습니다.")
|
| 1395 |
-
|
| 1396 |
-
filename = f"사례관리일지_{data['client_masked_name']}_{data['first_meeting_date']}.xlsx"
|
| 1397 |
-
if st.button("📦 엑셀 파일 준비하기", use_container_width=True, key="prepare_case_excel_fast"):
|
| 1398 |
-
st.session_state["case_excel_fast"] = generate_excel(data)
|
| 1399 |
-
st.success("엑셀 파일 준비가 완료되었습니다. 아래 다운로드 버튼을 눌러주세요.")
|
| 1400 |
-
|
| 1401 |
-
if "case_excel_fast" in st.session_state:
|
| 1402 |
-
st.download_button(
|
| 1403 |
-
"📥 사례관리 회의록 엑셀 다운로드",
|
| 1404 |
-
data=st.session_state["case_excel_fast"],
|
| 1405 |
-
file_name=filename,
|
| 1406 |
-
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 1407 |
-
use_container_width=True,
|
| 1408 |
-
key="download_case_excel_fast",
|
| 1409 |
-
)
|
| 1410 |
-
|
| 1411 |
-
st.caption("빠른 버전: 화면 생성 후, 엑셀은 필요할 때만 준비합니다.")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