Spaces:
No application file
No application file
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,935 +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 |
-
|
| 15 |
-
|
| 16 |
-
# =========================================================
|
| 17 |
-
# BeeCare 통합연동 상태변화기록지 생성기
|
| 18 |
-
# - Client Center 수급자 DB 연동
|
| 19 |
-
# - 모든 기관유형 기본 주 1회 작성
|
| 20 |
-
# - 필요 시 추가작성 가능
|
| 21 |
-
# - 상태변화 발생 시 급여제공계획 재작성 필요 여부 자동 판단
|
| 22 |
-
# - 상담일지/욕구사정/사례관리/급여계획과 연결 가능한 DB 저장
|
| 23 |
-
# - 엑셀 다운로드, 사진첨부, 평가 적합도 점검, 결재라인 2칸
|
| 24 |
-
# =========================================================
|
| 25 |
-
|
| 26 |
-
st.set_page_config(
|
| 27 |
-
page_title="상태변화기록지",
|
| 28 |
-
page_icon="🩺",
|
| 29 |
-
layout="wide"
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 33 |
-
|
| 34 |
-
DB_CANDIDATES = [
|
| 35 |
-
os.path.join(CURRENT_DIR, "data", "clients.db"),
|
| 36 |
-
os.path.join(CURRENT_DIR, "..", "Client Center", "data", "clients.db"),
|
| 37 |
-
os.path.join(CURRENT_DIR, "..", "ClientCenter", "data", "clients.db"),
|
| 38 |
-
os.path.join(CURRENT_DIR, "..", "Client_Center", "data", "clients.db"),
|
| 39 |
-
]
|
| 40 |
-
|
| 41 |
-
DB_PATH = None
|
| 42 |
-
for p in DB_CANDIDATES:
|
| 43 |
-
if os.path.exists(p):
|
| 44 |
-
DB_PATH = p
|
| 45 |
-
break
|
| 46 |
-
|
| 47 |
-
if DB_PATH is None:
|
| 48 |
-
os.makedirs(os.path.join(CURRENT_DIR, "data"), exist_ok=True)
|
| 49 |
-
DB_PATH = os.path.join(CURRENT_DIR, "data", "clients.db")
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
# -----------------------------
|
| 53 |
-
# UI 디자인
|
| 54 |
-
# -----------------------------
|
| 55 |
-
st.markdown("""
|
| 56 |
-
<style>
|
| 57 |
-
.block-container { padding-top: 2rem; }
|
| 58 |
-
.hero {
|
| 59 |
-
background: linear-gradient(135deg, #1D4ED8, #60A5FA);
|
| 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 |
-
.dangerbox {
|
| 89 |
-
background: #ffebee;
|
| 90 |
-
border-left: 7px solid #e53935;
|
| 91 |
-
padding: 14px;
|
| 92 |
-
border-radius: 12px;
|
| 93 |
-
margin-bottom: 14px;
|
| 94 |
-
}
|
| 95 |
-
</style>
|
| 96 |
-
""", unsafe_allow_html=True)
|
| 97 |
-
|
| 98 |
-
st.markdown("""
|
| 99 |
-
<div class="hero">
|
| 100 |
-
<h1>🩺 상태변화기록지 생성기</h1>
|
| 101 |
-
<p>Client Center 수급자 정보와 연동하여 주 1회 상태변화기록 및 추가기록을 생성합니다.</p>
|
| 102 |
-
</div>
|
| 103 |
-
""", unsafe_allow_html=True)
|
| 104 |
-
|
| 105 |
-
st.markdown("""
|
| 106 |
-
<div class="notice">
|
| 107 |
-
<strong>작성 원칙:</strong> 모든 기관유형은 기본 주 1회 작성으로 설계하고, 낙상·입원·퇴원·욕창·식사량 감소·보호자 요청 등 특이사항 발생 시 추가작성할 수 있습니다.
|
| 108 |
-
</div>
|
| 109 |
-
""", unsafe_allow_html=True)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
# -----------------------------
|
| 113 |
-
# DB
|
| 114 |
-
# -----------------------------
|
| 115 |
-
def get_conn():
|
| 116 |
-
return sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
def init_db():
|
| 120 |
-
conn = get_conn()
|
| 121 |
-
cur = conn.cursor()
|
| 122 |
-
|
| 123 |
-
cur.execute("""
|
| 124 |
-
CREATE TABLE IF NOT EXISTS clients (
|
| 125 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 126 |
-
name TEXT NOT NULL,
|
| 127 |
-
masked_name TEXT,
|
| 128 |
-
gender TEXT,
|
| 129 |
-
birth_year TEXT,
|
| 130 |
-
care_grade TEXT,
|
| 131 |
-
institution_type TEXT,
|
| 132 |
-
institution_name TEXT,
|
| 133 |
-
admission_date TEXT,
|
| 134 |
-
main_condition TEXT,
|
| 135 |
-
cognitive_status TEXT,
|
| 136 |
-
mobility_status TEXT,
|
| 137 |
-
diet_status TEXT,
|
| 138 |
-
toileting_status TEXT,
|
| 139 |
-
guardian_name TEXT,
|
| 140 |
-
guardian_phone TEXT,
|
| 141 |
-
notes TEXT,
|
| 142 |
-
status TEXT DEFAULT '이용중',
|
| 143 |
-
created_at TEXT,
|
| 144 |
-
updated_at TEXT
|
| 145 |
-
)
|
| 146 |
-
""")
|
| 147 |
-
|
| 148 |
-
# Client Center v2 필드가 없을 경우 추가
|
| 149 |
-
new_columns = {
|
| 150 |
-
"previous_care_grade": "TEXT",
|
| 151 |
-
"plan_change_required": "TEXT DEFAULT '아니오'",
|
| 152 |
-
"plan_change_type": "TEXT",
|
| 153 |
-
"plan_change_reason": "TEXT",
|
| 154 |
-
"plan_change_date": "TEXT",
|
| 155 |
-
"plan_rewrite_status": "TEXT DEFAULT '해당없음'",
|
| 156 |
-
"service_end_reason": "TEXT",
|
| 157 |
-
"service_end_date": "TEXT",
|
| 158 |
-
"linked_document": "TEXT",
|
| 159 |
-
}
|
| 160 |
-
cur.execute("PRAGMA table_info(clients)")
|
| 161 |
-
existing_cols = [row[1] for row in cur.fetchall()]
|
| 162 |
-
for col, col_type in new_columns.items():
|
| 163 |
-
if col not in existing_cols:
|
| 164 |
-
cur.execute(f"ALTER TABLE clients ADD COLUMN {col} {col_type}")
|
| 165 |
-
|
| 166 |
-
cur.execute("""
|
| 167 |
-
CREATE TABLE IF NOT EXISTS status_change_records (
|
| 168 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 169 |
-
client_id INTEGER,
|
| 170 |
-
client_masked_name TEXT,
|
| 171 |
-
institution_type TEXT,
|
| 172 |
-
record_type TEXT,
|
| 173 |
-
record_date TEXT,
|
| 174 |
-
week_period TEXT,
|
| 175 |
-
writer TEXT,
|
| 176 |
-
change_category TEXT,
|
| 177 |
-
body_status TEXT,
|
| 178 |
-
cognitive_status TEXT,
|
| 179 |
-
emotion_status TEXT,
|
| 180 |
-
diet_status TEXT,
|
| 181 |
-
toileting_status TEXT,
|
| 182 |
-
mobility_status TEXT,
|
| 183 |
-
skin_status TEXT,
|
| 184 |
-
sleep_status TEXT,
|
| 185 |
-
program_status TEXT,
|
| 186 |
-
guardian_opinion TEXT,
|
| 187 |
-
staff_observation TEXT,
|
| 188 |
-
action_taken TEXT,
|
| 189 |
-
followup_plan TEXT,
|
| 190 |
-
plan_change_required TEXT,
|
| 191 |
-
plan_change_reason TEXT,
|
| 192 |
-
evaluation_score INTEGER,
|
| 193 |
-
missing_items TEXT,
|
| 194 |
-
compliance_result TEXT,
|
| 195 |
-
photo_count INTEGER,
|
| 196 |
-
created_at TEXT
|
| 197 |
-
)
|
| 198 |
-
""")
|
| 199 |
-
|
| 200 |
-
cur.execute("""
|
| 201 |
-
CREATE TABLE IF NOT EXISTS plan_change_logs (
|
| 202 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 203 |
-
client_id INTEGER,
|
| 204 |
-
client_masked_name TEXT,
|
| 205 |
-
institution_type TEXT,
|
| 206 |
-
change_type TEXT,
|
| 207 |
-
change_reason TEXT,
|
| 208 |
-
change_date TEXT,
|
| 209 |
-
linked_document TEXT,
|
| 210 |
-
plan_change_required TEXT,
|
| 211 |
-
plan_rewrite_status TEXT,
|
| 212 |
-
memo TEXT,
|
| 213 |
-
created_at TEXT
|
| 214 |
-
)
|
| 215 |
-
""")
|
| 216 |
-
|
| 217 |
-
conn.commit()
|
| 218 |
-
conn.close()
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
def load_clients():
|
| 222 |
-
conn = get_conn()
|
| 223 |
-
df = pd.read_sql_query("SELECT * FROM clients ORDER BY id DESC", conn)
|
| 224 |
-
conn.close()
|
| 225 |
-
return df
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
def load_status_records(client_id=None):
|
| 229 |
-
conn = get_conn()
|
| 230 |
-
try:
|
| 231 |
-
if client_id:
|
| 232 |
-
df = pd.read_sql_query(
|
| 233 |
-
"SELECT * FROM status_change_records WHERE client_id=? ORDER BY record_date DESC, id DESC",
|
| 234 |
-
conn,
|
| 235 |
-
params=(int(client_id),)
|
| 236 |
-
)
|
| 237 |
-
else:
|
| 238 |
-
df = pd.read_sql_query(
|
| 239 |
-
"SELECT * FROM status_change_records ORDER BY record_date DESC, id DESC",
|
| 240 |
-
conn
|
| 241 |
-
)
|
| 242 |
-
except Exception:
|
| 243 |
-
df = pd.DataFrame()
|
| 244 |
-
conn.close()
|
| 245 |
-
return df
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
def safe(row, key, default=""):
|
| 249 |
-
try:
|
| 250 |
-
v = row.get(key, default)
|
| 251 |
-
if pd.isna(v):
|
| 252 |
-
return default
|
| 253 |
-
return str(v)
|
| 254 |
-
except Exception:
|
| 255 |
-
return default
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
def mask_name(name):
|
| 259 |
-
name = str(name or "").strip()
|
| 260 |
-
if len(name) >= 3:
|
| 261 |
-
return name[0] + "○" + name[2:]
|
| 262 |
-
if len(name) == 2:
|
| 263 |
-
return name[0] + "○"
|
| 264 |
-
return name
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
def save_uploaded_photos(uploaded_files):
|
| 268 |
-
paths = []
|
| 269 |
-
for file in (uploaded_files or [])[:3]:
|
| 270 |
-
suffix = os.path.splitext(file.name)[1].lower() or ".png"
|
| 271 |
-
temp_path = os.path.join(tempfile.gettempdir(), f"status_photo_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{suffix}")
|
| 272 |
-
with open(temp_path, "wb") as f:
|
| 273 |
-
f.write(file.getbuffer())
|
| 274 |
-
paths.append(temp_path)
|
| 275 |
-
return paths
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
def save_plan_change_log(client_id, client_masked_name, institution_type, change_reason, record_date, required, memo):
|
| 279 |
-
conn = get_conn()
|
| 280 |
-
cur = conn.cursor()
|
| 281 |
-
|
| 282 |
-
rewrite_status = "재작성 필요" if required == "예" else "현재계획 유지"
|
| 283 |
-
|
| 284 |
-
cur.execute("""
|
| 285 |
-
INSERT INTO plan_change_logs (
|
| 286 |
-
client_id, client_masked_name, institution_type, change_type,
|
| 287 |
-
change_reason, change_date, linked_document, plan_change_required,
|
| 288 |
-
plan_rewrite_status, memo, created_at
|
| 289 |
-
)
|
| 290 |
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 291 |
-
""", (
|
| 292 |
-
client_id,
|
| 293 |
-
client_masked_name,
|
| 294 |
-
institution_type,
|
| 295 |
-
"상태변화",
|
| 296 |
-
change_reason,
|
| 297 |
-
record_date,
|
| 298 |
-
"상태변화기록지",
|
| 299 |
-
required,
|
| 300 |
-
rewrite_status,
|
| 301 |
-
memo,
|
| 302 |
-
datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 303 |
-
))
|
| 304 |
-
|
| 305 |
-
cur.execute("""
|
| 306 |
-
UPDATE clients
|
| 307 |
-
SET plan_change_required=?,
|
| 308 |
-
plan_change_type=?,
|
| 309 |
-
plan_change_reason=?,
|
| 310 |
-
plan_change_date=?,
|
| 311 |
-
plan_rewrite_status=?,
|
| 312 |
-
linked_document=?,
|
| 313 |
-
updated_at=?
|
| 314 |
-
WHERE id=?
|
| 315 |
-
""", (
|
| 316 |
-
required,
|
| 317 |
-
"상태변화",
|
| 318 |
-
change_reason,
|
| 319 |
-
record_date,
|
| 320 |
-
rewrite_status,
|
| 321 |
-
"상태변화기록지",
|
| 322 |
-
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 323 |
-
client_id
|
| 324 |
-
))
|
| 325 |
-
|
| 326 |
-
conn.commit()
|
| 327 |
-
conn.close()
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
def save_status_record(data):
|
| 331 |
-
conn = get_conn()
|
| 332 |
-
cur = conn.cursor()
|
| 333 |
-
cur.execute("""
|
| 334 |
-
INSERT INTO status_change_records (
|
| 335 |
-
client_id, client_masked_name, institution_type, record_type,
|
| 336 |
-
record_date, week_period, writer, change_category,
|
| 337 |
-
body_status, cognitive_status, emotion_status, diet_status,
|
| 338 |
-
toileting_status, mobility_status, skin_status, sleep_status,
|
| 339 |
-
program_status, guardian_opinion, staff_observation,
|
| 340 |
-
action_taken, followup_plan, plan_change_required,
|
| 341 |
-
plan_change_reason, evaluation_score, missing_items,
|
| 342 |
-
compliance_result, photo_count, created_at
|
| 343 |
-
)
|
| 344 |
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 345 |
-
""", (
|
| 346 |
-
data["client_id"],
|
| 347 |
-
data["client_masked_name"],
|
| 348 |
-
data["institution_type"],
|
| 349 |
-
data["record_type"],
|
| 350 |
-
data["record_date"],
|
| 351 |
-
data["week_period"],
|
| 352 |
-
data["writer"],
|
| 353 |
-
data["change_category"],
|
| 354 |
-
data["body_status"],
|
| 355 |
-
data["cognitive_status"],
|
| 356 |
-
data["emotion_status"],
|
| 357 |
-
data["diet_status"],
|
| 358 |
-
data["toileting_status"],
|
| 359 |
-
data["mobility_status"],
|
| 360 |
-
data["skin_status"],
|
| 361 |
-
data["sleep_status"],
|
| 362 |
-
data["program_status"],
|
| 363 |
-
data["guardian_opinion"],
|
| 364 |
-
data["staff_observation"],
|
| 365 |
-
data["action_taken"],
|
| 366 |
-
data["followup_plan"],
|
| 367 |
-
data["plan_change_required"],
|
| 368 |
-
data["plan_change_reason"],
|
| 369 |
-
data["evaluation_score"],
|
| 370 |
-
data["missing_items"],
|
| 371 |
-
data["compliance_result"],
|
| 372 |
-
data["photo_count"],
|
| 373 |
-
datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 374 |
-
))
|
| 375 |
-
conn.commit()
|
| 376 |
-
conn.close()
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
init_db()
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
# -----------------------------
|
| 383 |
-
# 기관유형별 추가 점검 항목
|
| 384 |
-
# -----------------------------
|
| 385 |
-
INSTITUTION_GUIDES = {
|
| 386 |
-
"방문요양": {
|
| 387 |
-
"focus": ["재가생활 변화", "보행/이동", "식사·복약", "인지활동", "가사지원 범위", "보호자 요청"],
|
| 388 |
-
"note": "방문서비스 제공 중 확인된 상태변화와 보호자 의견, 요양보호사 관찰내용을 중심으로 기록합니다.",
|
| 389 |
-
},
|
| 390 |
-
"방문목욕": {
|
| 391 |
-
"focus": ["피부상태", "목욕협조도", "목욕 전후 활력", "이동안전", "청결상태", "보호자 협조"],
|
| 392 |
-
"note": "목욕 전후 건강상태, 피부 발적·상처, 이동안전과 목욕 거부 여부를 중심으로 기록합니다.",
|
| 393 |
-
},
|
| 394 |
-
"방문간호": {
|
| 395 |
-
"focus": ["혈압/혈당", "상처관리", "투약변경", "건강상담", "의료연계", "보호자 교육"],
|
| 396 |
-
"note": "건강지표 변화, 처치 내용, 투약·상처·의료연계 필요성을 중심으로 기록합니다.",
|
| 397 |
-
},
|
| 398 |
-
"주간보호": {
|
| 399 |
-
"focus": ["프로그램 참여", "식사", "배변", "정서", "사회성", "송영안전", "낙상위험"],
|
| 400 |
-
"note": "센터 이용 중 한 주간의 신체·인지·정서·식사·배변·프로그램 참여 변화를 요약합니다.",
|
| 401 |
-
},
|
| 402 |
-
"요양원": {
|
| 403 |
-
"focus": ["식사", "수면", "욕창", "낙상", "인지", "배변", "프로그램", "정서지원"],
|
| 404 |
-
"note": "매일 관찰기록과 별도로 주 1회 이상 상태변화를 요약하고, 급격한 변화는 추가작성합니다.",
|
| 405 |
-
},
|
| 406 |
-
"공동생활가정": {
|
| 407 |
-
"focus": ["생활적응", "정서안정", "사회관계", "프로그램 참여", "식사", "개별 욕구", "가족소통"],
|
| 408 |
-
"note": "소규모 공동생활 적응, 정서·사회관계 변화, 개별욕구와 가족소통 변화를 중심으로 기록합니다.",
|
| 409 |
-
},
|
| 410 |
-
}
|
| 411 |
-
|
| 412 |
-
CHANGE_CATEGORIES = [
|
| 413 |
-
"특이변화 없음",
|
| 414 |
-
"낙상 발생/위험 증가",
|
| 415 |
-
"욕창 발생/위험 증가",
|
| 416 |
-
"식사량 감소",
|
| 417 |
-
"수분섭취 저하",
|
| 418 |
-
"체중감소 우려",
|
| 419 |
-
"보행능력 저하",
|
| 420 |
-
"인지기능 저하",
|
| 421 |
-
"정서불안/우울감",
|
| 422 |
-
"배변/배뇨 변화",
|
| 423 |
-
"기저귀 착용 시작/증가",
|
| 424 |
-
"피부상태 변화",
|
| 425 |
-
"수면상태 변화",
|
| 426 |
-
"복약/건강상태 변화",
|
| 427 |
-
"병원진료/입원",
|
| 428 |
-
"퇴원 후 재이용",
|
| 429 |
-
"등급변경",
|
| 430 |
-
"보호자 요청",
|
| 431 |
-
"서비스 변경 필요",
|
| 432 |
-
"사망/전원/서비스 종료",
|
| 433 |
-
"기타",
|
| 434 |
-
]
|
| 435 |
-
|
| 436 |
-
PLAN_CHANGE_TRIGGER_WORDS = [
|
| 437 |
-
"낙상", "욕창", "식사량 감소", "수분섭취", "체중", "보행능력 저하",
|
| 438 |
-
"인지기능 저하", "정서불안", "배변", "기저귀", "피부상태 변화",
|
| 439 |
-
"수면상태 변화", "복약", "입원", "퇴원", "등급변경", "보호자 요청", "서비스 변경"
|
| 440 |
-
]
|
| 441 |
-
|
| 442 |
-
TERMINATION_WORDS = ["사망", "전원", "서비스 종료"]
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
def determine_plan_change(change_category, body_status, cognitive_status, diet_status, mobility_status, skin_status, guardian_opinion, action_taken):
|
| 446 |
-
combined = " ".join([
|
| 447 |
-
change_category, body_status, cognitive_status, diet_status,
|
| 448 |
-
mobility_status, skin_status, guardian_opinion, action_taken
|
| 449 |
-
])
|
| 450 |
-
|
| 451 |
-
if any(w in combined for w in TERMINATION_WORDS):
|
| 452 |
-
return "아니오", "사망·전원·서비스 종료 사유는 급여제공계획 재작성보다 종결/중지 기록 정리가 우선입니다."
|
| 453 |
-
|
| 454 |
-
if change_category == "특이변화 없음":
|
| 455 |
-
return "아니오", "특이 상태변화가 없어 현재 급여제공계획을 유지합니다."
|
| 456 |
-
|
| 457 |
-
if any(w in combined for w in PLAN_CHANGE_TRIGGER_WORDS):
|
| 458 |
-
return "예", "상태변화가 확인되어 상담일지·욕구사정·사례관리와 연동하여 급여제공계획 재작성 여부를 검토해야 합니다."
|
| 459 |
-
|
| 460 |
-
return "검토", "상태변화 내용이 있으므로 담당자 확인 후 급여제공계획 반영 여부를 판단합니다."
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
def build_status_text(client, institution_type, record_type, change_category, body_status, cognitive_status, emotion_status,
|
| 464 |
-
diet_status, toileting_status, mobility_status, skin_status, sleep_status, program_status,
|
| 465 |
-
guardian_opinion, staff_observation, action_taken, followup_plan):
|
| 466 |
-
focus = ", ".join(INSTITUTION_GUIDES[institution_type]["focus"])
|
| 467 |
-
opener = random.choice([
|
| 468 |
-
"이번 주 수급자의 전반적인 상태를 관찰한 결과",
|
| 469 |
-
"서비스 제공 과정에서 확인된 상태변화를 종합하면",
|
| 470 |
-
"주간 관찰 및 종사자 의견을 종합한 결과",
|
| 471 |
-
"수급자의 신체·인지·정서 상태를 함께 확인한 결과",
|
| 472 |
-
])
|
| 473 |
-
|
| 474 |
-
if record_type == "추가작성":
|
| 475 |
-
opener = random.choice([
|
| 476 |
-
"특이사항 발생으로 추가 상태변화기록을 작성함.",
|
| 477 |
-
"정기 주간기록 외에 즉시 확인이 필요한 변화가 있어 추가 기록함.",
|
| 478 |
-
"상태변화 발생에 따라 급여제공 방향 검토를 위해 추가 기록함.",
|
| 479 |
-
])
|
| 480 |
-
|
| 481 |
-
text = f"""
|
| 482 |
-
{opener}
|
| 483 |
-
|
| 484 |
-
[기록구분]
|
| 485 |
-
{record_type}
|
| 486 |
-
|
| 487 |
-
[기관유형별 중점 확인]
|
| 488 |
-
{institution_type}에서는 {focus} 항목을 중심으로 상태변화를 확인합니다.
|
| 489 |
-
{INSTITUTION_GUIDES[institution_type]["note"]}
|
| 490 |
-
|
| 491 |
-
[상태변화 분류]
|
| 492 |
-
{change_category}
|
| 493 |
-
|
| 494 |
-
[세부 관찰내용]
|
| 495 |
-
- 신체상태: {body_status or '특이사항 없음'}
|
| 496 |
-
- 인지상태: {cognitive_status or '특이사항 없음'}
|
| 497 |
-
- 정서상태: {emotion_status or '특이사항 없음'}
|
| 498 |
-
- 식사상태: {diet_status or '특이사항 없음'}
|
| 499 |
-
- 배변/배뇨상태: {toileting_status or '특이사항 없음'}
|
| 500 |
-
- 이동상태: {mobility_status or '특이사항 없음'}
|
| 501 |
-
- 피부상태: {skin_status or '특이사항 없음'}
|
| 502 |
-
- 수면상태: {sleep_status or '특이사항 없음'}
|
| 503 |
-
- 프로그램/활동상태: {program_status or '해당 없음'}
|
| 504 |
-
|
| 505 |
-
[보호자 의견]
|
| 506 |
-
{guardian_opinion or '보호자 의견은 특이사항 없으며, 필요 시 상담일지로 추가 확인 예정'}
|
| 507 |
-
|
| 508 |
-
[종사자 관찰사항]
|
| 509 |
-
{staff_observation or '급여제공 중 특이사항은 없으나 지속 관찰 필요'}
|
| 510 |
-
|
| 511 |
-
[조치내용]
|
| 512 |
-
{action_taken or '상태를 지속 관찰하고 필요 시 담당자 및 보호자에게 공유'}
|
| 513 |
-
|
| 514 |
-
[후속계획]
|
| 515 |
-
{followup_plan or '다음 주 상태변화를 재확인하고, 변화가 지속될 경우 상담일지·욕구사정·급여제공계획에 반영 여부를 검토'}
|
| 516 |
-
""".strip()
|
| 517 |
-
|
| 518 |
-
return text
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
def evaluate_record(record_type, change_category, status_text, guardian_opinion, staff_observation, action_taken, followup_plan, plan_change_required):
|
| 522 |
-
required = {
|
| 523 |
-
"기록구분": bool(record_type),
|
| 524 |
-
"상태변화 분류": bool(change_category),
|
| 525 |
-
"신체/인지/정서 등 관찰": "세부 관찰내용" in status_text,
|
| 526 |
-
"보호자 의견 확인": bool(guardian_opinion.strip()) or "보호자 의견" in status_text,
|
| 527 |
-
"종사자 관찰 반영": bool(staff_observation.strip()) or "종사자 관찰" in status_text,
|
| 528 |
-
"조치내용": bool(action_taken.strip()) or "조치내용" in status_text,
|
| 529 |
-
"후속계획": bool(followup_plan.strip()) or "후속계획" in status_text,
|
| 530 |
-
"급여계획 연계 판단": plan_change_required in ["예", "아니오", "검토"],
|
| 531 |
-
}
|
| 532 |
-
|
| 533 |
-
score = int(sum(required.values()) / len(required) * 100)
|
| 534 |
-
missing = [k for k, v in required.items() if not v]
|
| 535 |
-
|
| 536 |
-
if score >= 90:
|
| 537 |
-
result = "평가 적합도가 높습니다. 상태변화, 조치, 후속계획, 급여계획 연계 판단이 잘 반영되었습니다."
|
| 538 |
-
elif score >= 75:
|
| 539 |
-
result = "대체로 적합하나 일부 보완이 필요합니다. 부족 항목을 추가하면 기록 완성도가 높아집니다."
|
| 540 |
-
else:
|
| 541 |
-
result = "보완이 필요합니다. 상태변화, 보호자 의견, 조치내용, 후속계획이 구체적으로 들어가야 합니다."
|
| 542 |
-
|
| 543 |
-
return score, missing, result
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
# -----------------------------
|
| 547 |
-
# 엑셀
|
| 548 |
-
# -----------------------------
|
| 549 |
-
def style_ws(ws, max_row):
|
| 550 |
-
"""A4 출력 시 선이 잘리지 않도록 전체 출력범위에 테두리/정렬을 적용합니다."""
|
| 551 |
-
thin = Side(style="thin", color="000000")
|
| 552 |
-
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 553 |
-
|
| 554 |
-
for row in ws.iter_rows(min_row=1, max_row=max_row, min_col=1, max_col=9):
|
| 555 |
-
for cell in row:
|
| 556 |
-
cell.border = border
|
| 557 |
-
if cell.value is not None:
|
| 558 |
-
current_size = cell.font.sz or 10
|
| 559 |
-
cell.font = Font(
|
| 560 |
-
name="Malgun Gothic",
|
| 561 |
-
size=current_size,
|
| 562 |
-
bold=cell.font.bold
|
| 563 |
-
)
|
| 564 |
-
else:
|
| 565 |
-
cell.font = Font(name="Malgun Gothic", size=10)
|
| 566 |
-
cell.alignment = Alignment(
|
| 567 |
-
horizontal=cell.alignment.horizontal or "left",
|
| 568 |
-
vertical=cell.alignment.vertical or "center",
|
| 569 |
-
wrap_text=True
|
| 570 |
-
)
|
| 571 |
-
|
| 572 |
-
# 보기 좋게 출력되도록 열 너비 조정
|
| 573 |
-
widths = {1: 11, 2: 13, 3: 13, 4: 11, 5: 13, 6: 13, 7: 11, 8: 13, 9: 13}
|
| 574 |
-
for col, width in widths.items():
|
| 575 |
-
ws.column_dimensions[get_column_letter(col)].width = width
|
| 576 |
-
|
| 577 |
-
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
| 578 |
-
ws.page_setup.orientation = "portrait"
|
| 579 |
-
ws.page_setup.fitToWidth = 1
|
| 580 |
-
ws.page_setup.fitToHeight = 0
|
| 581 |
-
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
| 582 |
-
ws.page_margins.left = 0.25
|
| 583 |
-
ws.page_margins.right = 0.25
|
| 584 |
-
ws.page_margins.top = 0.30
|
| 585 |
-
ws.page_margins.bottom = 0.30
|
| 586 |
-
ws.sheet_view.showGridLines = False
|
| 587 |
-
ws.print_area = f"A1:I{max_row}"
|
| 588 |
-
ws.print_options.horizontalCentered = True
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
def write_title_with_approval(ws, title, title_fill, header_fill):
|
| 592 |
-
"""큰 제목은 왼쪽 A:G, 결재라인은 오른쪽 맨 위 H:I에 고정합니다."""
|
| 593 |
-
for col in range(1, 10):
|
| 594 |
-
ws.column_dimensions[get_column_letter(col)].width = 12
|
| 595 |
-
|
| 596 |
-
thin = Side(style="thin", color="000000")
|
| 597 |
-
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 598 |
-
|
| 599 |
-
ws.merge_cells(start_row=1, start_column=1, end_row=2, end_column=7)
|
| 600 |
-
title_cell = ws.cell(1, 1)
|
| 601 |
-
title_cell.value = title
|
| 602 |
-
title_cell.font = Font(name="Malgun Gothic", size=24, bold=True)
|
| 603 |
-
title_cell.alignment = Alignment(horizontal="center", vertical="center")
|
| 604 |
-
title_cell.fill = title_fill
|
| 605 |
-
|
| 606 |
-
# 제목 병합 영역 전체 테두리 적용
|
| 607 |
-
for rr in [1, 2]:
|
| 608 |
-
for cc in range(1, 8):
|
| 609 |
-
cell = ws.cell(rr, cc)
|
| 610 |
-
cell.border = border
|
| 611 |
-
cell.fill = title_fill
|
| 612 |
-
|
| 613 |
-
# 결재라인 오른쪽 맨 위 고정: H:I만 사용
|
| 614 |
-
approval = {
|
| 615 |
-
(1, 8): "담당자",
|
| 616 |
-
(1, 9): "시설장",
|
| 617 |
-
(2, 8): "",
|
| 618 |
-
(2, 9): "",
|
| 619 |
-
}
|
| 620 |
-
for (rr, cc), value in approval.items():
|
| 621 |
-
cell = ws.cell(rr, cc)
|
| 622 |
-
cell.value = value
|
| 623 |
-
cell.border = border
|
| 624 |
-
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 625 |
-
cell.font = Font(name="Malgun Gothic", size=11, bold=(rr == 1))
|
| 626 |
-
if rr == 1:
|
| 627 |
-
cell.fill = header_fill
|
| 628 |
-
|
| 629 |
-
ws.row_dimensions[1].height = 28
|
| 630 |
-
ws.row_dimensions[2].height = 42
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
def write_info_row(ws, row, a, b, c, d, e, f, header_fill):
|
| 634 |
-
ws.cell(row, 1).value = a
|
| 635 |
-
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=3)
|
| 636 |
-
ws.cell(row, 2).value = b
|
| 637 |
-
ws.cell(row, 4).value = c
|
| 638 |
-
ws.merge_cells(start_row=row, start_column=5, end_row=row, end_column=6)
|
| 639 |
-
ws.cell(row, 5).value = d
|
| 640 |
-
ws.cell(row, 7).value = e
|
| 641 |
-
ws.merge_cells(start_row=row, start_column=8, end_row=row, end_column=9)
|
| 642 |
-
ws.cell(row, 8).value = f
|
| 643 |
-
|
| 644 |
-
for col in [1, 4, 7]:
|
| 645 |
-
ws.cell(row, col).fill = header_fill
|
| 646 |
-
ws.cell(row, col).font = Font(name="Malgun Gothic", size=11, bold=True)
|
| 647 |
-
ws.cell(row, col).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 648 |
-
|
| 649 |
-
for col in [2, 5, 8]:
|
| 650 |
-
ws.cell(row, col).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
| 651 |
-
|
| 652 |
-
ws.row_dimensions[row].height = 30
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
def write_section(ws, row, title, content, header_fill, height=100):
|
| 656 |
-
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
|
| 657 |
-
ws.cell(row, 1).value = title
|
| 658 |
-
ws.cell(row, 1).font = Font(name="Malgun Gothic", size=15, bold=True)
|
| 659 |
-
ws.cell(row, 1).alignment = Alignment(horizontal="center", vertical="center")
|
| 660 |
-
ws.cell(row, 1).fill = header_fill
|
| 661 |
-
ws.row_dimensions[row].height = 30
|
| 662 |
-
row += 1
|
| 663 |
-
|
| 664 |
-
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
|
| 665 |
-
ws.cell(row, 1).value = content
|
| 666 |
-
ws.cell(row, 1).font = Font(name="Malgun Gothic", size=11)
|
| 667 |
-
ws.cell(row, 1).alignment = Alignment(horizontal="left", vertical="top", wrap_text=True)
|
| 668 |
-
lines = len(str(content)) // 60 + 1 + str(content).count("\n")
|
| 669 |
-
ws.row_dimensions[row].height = max(height, lines * 18)
|
| 670 |
-
return row + 1
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
def generate_excel(data):
|
| 674 |
-
wb = Workbook()
|
| 675 |
-
title_fill = PatternFill("solid", fgColor="DBEAFE")
|
| 676 |
-
header_fill = PatternFill("solid", fgColor="F3F4F6")
|
| 677 |
-
|
| 678 |
-
ws = wb.active
|
| 679 |
-
ws.title = "상태변화기록지"
|
| 680 |
-
write_title_with_approval(ws, "상태변화기록지", title_fill, header_fill)
|
| 681 |
-
|
| 682 |
-
r = 3
|
| 683 |
-
write_info_row(ws, r, "기관명", data["institution_name"], "기관유형", data["institution_type"], "기록일자", data["record_date"], header_fill); r += 1
|
| 684 |
-
write_info_row(ws, r, "수급자", data["client_masked_name"], "장기요양등급", data["grade"], "기록구분", data["record_type"], header_fill); r += 1
|
| 685 |
-
write_info_row(ws, r, "작성자", data["writer"], "주간기간", data["week_period"], "재작성필요", data["plan_change_required"], header_fill); r += 1
|
| 686 |
-
|
| 687 |
-
r = write_section(ws, r, "상태변화 기록내용", data["status_text"], header_fill, 240)
|
| 688 |
-
r = write_section(ws, r, "급여제공계획 연계 판단", data["plan_change_reason"], header_fill, 70)
|
| 689 |
-
|
| 690 |
-
# 평가 적합도는 출력물에는 보이지 않도록 내부점검 시트로만 관리
|
| 691 |
-
internal_ws = wb.create_sheet("내부점검자료_출력제외")
|
| 692 |
-
internal_ws.sheet_state = "hidden"
|
| 693 |
-
internal_ws.cell(1, 1).value = "평가 적합도"
|
| 694 |
-
internal_ws.cell(1, 2).value = f"{data['evaluation_score']}점"
|
| 695 |
-
internal_ws.cell(2, 1).value = "부족 항목"
|
| 696 |
-
internal_ws.cell(2, 2).value = data["missing_items"]
|
| 697 |
-
internal_ws.cell(3, 1).value = "점검 결과"
|
| 698 |
-
internal_ws.cell(3, 2).value = data["compliance_result"]
|
| 699 |
-
for row in internal_ws.iter_rows(min_row=1, max_row=3, min_col=1, max_col=2):
|
| 700 |
-
for cell in row:
|
| 701 |
-
cell.font = Font(name="Malgun Gothic", size=10)
|
| 702 |
-
cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
| 703 |
-
|
| 704 |
-
# 사진첨부
|
| 705 |
-
if data.get("photo_paths"):
|
| 706 |
-
ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=9)
|
| 707 |
-
ws.cell(r, 1).value = "사진첨부"
|
| 708 |
-
ws.cell(r, 1).font = Font(name="Malgun Gothic", size=15, bold=True)
|
| 709 |
-
ws.cell(r, 1).alignment = Alignment(horizontal="center", vertical="center")
|
| 710 |
-
ws.cell(r, 1).fill = header_fill
|
| 711 |
-
r += 1
|
| 712 |
-
|
| 713 |
-
anchors = ["A", "D", "G"]
|
| 714 |
-
img_row = r
|
| 715 |
-
for idx, photo_path in enumerate(data.get("photo_paths", [])[:3]):
|
| 716 |
-
try:
|
| 717 |
-
img = XLImage(photo_path)
|
| 718 |
-
img.width = 210
|
| 719 |
-
img.height = 150
|
| 720 |
-
ws.add_image(img, f"{anchors[idx]}{img_row}")
|
| 721 |
-
except Exception:
|
| 722 |
-
pass
|
| 723 |
-
|
| 724 |
-
for rr in range(img_row, img_row + 8):
|
| 725 |
-
ws.row_dimensions[rr].height = 22
|
| 726 |
-
r = img_row + 8
|
| 727 |
-
|
| 728 |
-
style_ws(ws, r)
|
| 729 |
-
|
| 730 |
-
output = BytesIO()
|
| 731 |
-
wb.save(output)
|
| 732 |
-
output.seek(0)
|
| 733 |
-
return output
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
# -----------------------------
|
| 737 |
-
# 화면
|
| 738 |
-
# -----------------------------
|
| 739 |
-
menu = st.sidebar.radio("메뉴", ["상태변화기록 생성", "저장기록 보기"])
|
| 740 |
-
|
| 741 |
-
st.sidebar.success("DB 연결")
|
| 742 |
-
st.sidebar.caption(DB_PATH)
|
| 743 |
-
|
| 744 |
-
clients_df = load_clients()
|
| 745 |
-
|
| 746 |
-
if menu == "상태변화기록 생성":
|
| 747 |
-
if clients_df.empty:
|
| 748 |
-
st.warning("Client Center 수급자 DB가 비어 있습니다. 먼저 수급자를 등록하세요.")
|
| 749 |
-
st.stop()
|
| 750 |
-
|
| 751 |
-
options = clients_df.apply(
|
| 752 |
-
lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_type']} / {x.get('status','')}",
|
| 753 |
-
axis=1
|
| 754 |
-
).tolist()
|
| 755 |
-
|
| 756 |
-
selected_option = st.selectbox("수급자 선택", options)
|
| 757 |
-
selected_id = int(selected_option.split("번")[0])
|
| 758 |
-
client = clients_df[clients_df["id"] == selected_id].iloc[0]
|
| 759 |
-
|
| 760 |
-
client_id = int(safe(client, "id", 0) or 0)
|
| 761 |
-
institution_type = safe(client, "institution_type", "방문요양")
|
| 762 |
-
if institution_type not in INSTITUTION_GUIDES:
|
| 763 |
-
institution_type = "방문요양"
|
| 764 |
-
|
| 765 |
-
m1, m2, m3, m4 = st.columns(4)
|
| 766 |
-
m1.metric("수급자", safe(client, "masked_name"))
|
| 767 |
-
m2.metric("등급", safe(client, "care_grade"))
|
| 768 |
-
m3.metric("기관유형", institution_type)
|
| 769 |
-
m4.metric("작성주기", "주 1회 기본")
|
| 770 |
-
|
| 771 |
-
st.info(INSTITUTION_GUIDES[institution_type]["note"])
|
| 772 |
-
|
| 773 |
-
st.markdown("### 기록 기본정보")
|
| 774 |
-
col1, col2, col3 = st.columns(3)
|
| 775 |
-
|
| 776 |
-
record_type = col1.radio("기록구분", ["주간 정기기록", "추가작성"], horizontal=True)
|
| 777 |
-
record_date = col2.date_input("기록일자", value=date.today())
|
| 778 |
-
writer = col3.text_input("작성자", "사회복지사")
|
| 779 |
-
|
| 780 |
-
week_start = record_date - timedelta(days=record_date.weekday())
|
| 781 |
-
week_end = week_start + timedelta(days=6)
|
| 782 |
-
week_period = st.text_input("주간기간", value=f"{week_start} ~ {week_end}")
|
| 783 |
-
|
| 784 |
-
st.markdown("### 상태변화 분류")
|
| 785 |
-
change_category = st.selectbox("상태변화 분류", CHANGE_CATEGORIES)
|
| 786 |
-
|
| 787 |
-
st.markdown("### 세부 상태 입력")
|
| 788 |
-
c1, c2 = st.columns(2)
|
| 789 |
-
|
| 790 |
-
with c1:
|
| 791 |
-
body_status = st.text_area("신체상태 변화", placeholder="예: 보행 시 휘청거림 증가, 통증 호소 등", height=90)
|
| 792 |
-
cognitive_status = st.text_area("인지상태 변화", placeholder="예: 반복질문 증가, 시간/장소 혼동 등", height=90)
|
| 793 |
-
emotion_status = st.text_area("정서상태 변화", placeholder="예: 불안, 우울감, 짜증 증가 등", height=90)
|
| 794 |
-
diet_status = st.text_area("식사상태 변화", placeholder="예: 식사량 감소, 사레, 연하곤란 등", height=90)
|
| 795 |
-
toileting_status = st.text_area("배변/배뇨 변화", placeholder="예: 변비, 설사, 실금, 기저귀 사용 증가 등", height=90)
|
| 796 |
-
|
| 797 |
-
with c2:
|
| 798 |
-
mobility_status = st.text_area("이동상태 변화", placeholder="예: 부축 필요 증가, 휠체어 이동으로 변경 등", height=90)
|
| 799 |
-
skin_status = st.text_area("피부상태 변화", placeholder="예: 발적, ��처, 욕창 위험 등", height=90)
|
| 800 |
-
sleep_status = st.text_area("수면상태 변화", placeholder="예: 야간각성, 낮잠 증가 등", height=90)
|
| 801 |
-
program_status = st.text_area("프로그램/활동 변화", placeholder="예: 참여 저조, 흥미 저하 등", height=90)
|
| 802 |
-
guardian_opinion = st.text_area("보호자 의견", placeholder="예: 보호자가 식사량 감소를 걱정함 등", height=90)
|
| 803 |
-
|
| 804 |
-
staff_observation = st.text_area("종사자 관찰사항", placeholder="예: 요양보호사/간호조무사가 관찰한 변화", height=90)
|
| 805 |
-
action_taken = st.text_area("조치내용", placeholder="예: 보호자에게 공유, 병원진료 권유, 환경정리, 식사보조 강화 등", height=90)
|
| 806 |
-
followup_plan = st.text_area("후속계획", placeholder="예: 다음 주 재확인, 상담일지 작성, 욕구사정 재점검, 급여계획 변경 검토 등", height=90)
|
| 807 |
-
|
| 808 |
-
photos = st.file_uploader("사진첨부 (최대 3장, 선택사항)", type=["png", "jpg", "jpeg"], accept_multiple_files=True)
|
| 809 |
-
|
| 810 |
-
required, plan_reason = determine_plan_change(
|
| 811 |
-
change_category, body_status, cognitive_status, diet_status,
|
| 812 |
-
mobility_status, skin_status, guardian_opinion, action_taken
|
| 813 |
-
)
|
| 814 |
-
|
| 815 |
-
st.markdown("### 급여제공계획 연계 판단")
|
| 816 |
-
p1, p2 = st.columns(2)
|
| 817 |
-
p1.metric("급여계획 재작성 필요", required)
|
| 818 |
-
p2.metric("연동문서", "상태변화기록지")
|
| 819 |
-
|
| 820 |
-
if required == "예":
|
| 821 |
-
st.markdown(f'<div class="dangerbox">{plan_reason}</div>', unsafe_allow_html=True)
|
| 822 |
-
elif required == "검토":
|
| 823 |
-
st.markdown(f'<div class="warnbox">{plan_reason}</div>', unsafe_allow_html=True)
|
| 824 |
-
else:
|
| 825 |
-
st.markdown(f'<div class="okbox">{plan_reason}</div>', unsafe_allow_html=True)
|
| 826 |
-
|
| 827 |
-
if st.button("🩺 상태변화기록 생성", use_container_width=True):
|
| 828 |
-
status_text = build_status_text(
|
| 829 |
-
client, institution_type, record_type, change_category,
|
| 830 |
-
body_status, cognitive_status, emotion_status, diet_status,
|
| 831 |
-
toileting_status, mobility_status, skin_status, sleep_status,
|
| 832 |
-
program_status, guardian_opinion, staff_observation, action_taken, followup_plan
|
| 833 |
-
)
|
| 834 |
-
|
| 835 |
-
score, missing, compliance = evaluate_record(
|
| 836 |
-
record_type, change_category, status_text, guardian_opinion,
|
| 837 |
-
staff_observation, action_taken, followup_plan, required
|
| 838 |
-
)
|
| 839 |
-
|
| 840 |
-
photo_paths = save_uploaded_photos(photos)
|
| 841 |
-
|
| 842 |
-
st.session_state["status_data"] = {
|
| 843 |
-
"client_id": client_id,
|
| 844 |
-
"client_masked_name": safe(client, "masked_name"),
|
| 845 |
-
"institution_name": safe(client, "institution_name"),
|
| 846 |
-
"institution_type": institution_type,
|
| 847 |
-
"grade": safe(client, "care_grade"),
|
| 848 |
-
"record_type": record_type,
|
| 849 |
-
"record_date": str(record_date),
|
| 850 |
-
"week_period": week_period,
|
| 851 |
-
"writer": writer,
|
| 852 |
-
"change_category": change_category,
|
| 853 |
-
"body_status": body_status,
|
| 854 |
-
"cognitive_status": cognitive_status,
|
| 855 |
-
"emotion_status": emotion_status,
|
| 856 |
-
"diet_status": diet_status,
|
| 857 |
-
"toileting_status": toileting_status,
|
| 858 |
-
"mobility_status": mobility_status,
|
| 859 |
-
"skin_status": skin_status,
|
| 860 |
-
"sleep_status": sleep_status,
|
| 861 |
-
"program_status": program_status,
|
| 862 |
-
"guardian_opinion": guardian_opinion,
|
| 863 |
-
"staff_observation": staff_observation,
|
| 864 |
-
"action_taken": action_taken,
|
| 865 |
-
"followup_plan": followup_plan,
|
| 866 |
-
"status_text": status_text,
|
| 867 |
-
"plan_change_required": required,
|
| 868 |
-
"plan_change_reason": plan_reason,
|
| 869 |
-
"evaluation_score": score,
|
| 870 |
-
"missing_items": ", ".join(missing) if missing else "부족 항목 없음",
|
| 871 |
-
"compliance_result": compliance,
|
| 872 |
-
"photo_paths": photo_paths,
|
| 873 |
-
"photo_count": len(photo_paths),
|
| 874 |
-
}
|
| 875 |
-
|
| 876 |
-
if "status_data" in st.session_state:
|
| 877 |
-
data = st.session_state["status_data"]
|
| 878 |
-
|
| 879 |
-
st.markdown("---")
|
| 880 |
-
st.subheader("생성 결과 수정")
|
| 881 |
-
data["status_text"] = st.text_area("상태변화 기록내용", value=data["status_text"], height=320)
|
| 882 |
-
data["plan_change_reason"] = st.text_area("급여계획 연계 판단 문구", value=data["plan_change_reason"], height=90)
|
| 883 |
-
|
| 884 |
-
score, missing, compliance = evaluate_record(
|
| 885 |
-
data["record_type"], data["change_category"], data["status_text"],
|
| 886 |
-
data["guardian_opinion"], data["staff_observation"], data["action_taken"],
|
| 887 |
-
data["followup_plan"], data["plan_change_required"]
|
| 888 |
-
)
|
| 889 |
-
|
| 890 |
-
data["evaluation_score"] = score
|
| 891 |
-
data["missing_items"] = ", ".join(missing) if missing else "부족 항목 없음"
|
| 892 |
-
data["compliance_result"] = compliance
|
| 893 |
-
|
| 894 |
-
st.subheader("평가 적합도 점검")
|
| 895 |
-
e1, e2, e3 = st.columns(3)
|
| 896 |
-
e1.metric("평가 적합도", f"{score}점")
|
| 897 |
-
e2.metric("부족 항목", data["missing_items"])
|
| 898 |
-
e3.metric("재작성 필요", data["plan_change_required"])
|
| 899 |
-
|
| 900 |
-
if score >= 90:
|
| 901 |
-
st.markdown(f'<div class="okbox">{compliance}</div>', unsafe_allow_html=True)
|
| 902 |
-
else:
|
| 903 |
-
st.markdown(f'<div class="warnbox">{compliance}</div>', unsafe_allow_html=True)
|
| 904 |
-
|
| 905 |
-
if st.button("💾 상태변화기록 DB 저장 및 Client Center 반영", use_container_width=True):
|
| 906 |
-
save_status_record(data)
|
| 907 |
-
save_plan_change_log(
|
| 908 |
-
data["client_id"],
|
| 909 |
-
data["client_masked_name"],
|
| 910 |
-
data["institution_type"],
|
| 911 |
-
data["plan_change_reason"],
|
| 912 |
-
data["record_date"],
|
| 913 |
-
data["plan_change_required"],
|
| 914 |
-
data["plan_change_reason"]
|
| 915 |
-
)
|
| 916 |
-
st.success("상태변화기록이 저장되었고 Client Center 급여계획 변경관리에도 반영되었습니다.")
|
| 917 |
-
|
| 918 |
-
filename = f"상태변화기록지_{data['client_masked_name']}_{data['record_date']}.xlsx"
|
| 919 |
-
st.download_button(
|
| 920 |
-
"📥 상태변화기록지 엑셀 다운로드",
|
| 921 |
-
data=generate_excel(data),
|
| 922 |
-
file_name=filename,
|
| 923 |
-
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 924 |
-
use_container_width=True,
|
| 925 |
-
)
|
| 926 |
-
|
| 927 |
-
elif menu == "저장기록 보기":
|
| 928 |
-
st.subheader("📚 저장된 상태변화기록")
|
| 929 |
-
df = load_status_records()
|
| 930 |
-
if df.empty:
|
| 931 |
-
st.info("저장된 상태변화기록이 없습니다.")
|
| 932 |
-
else:
|
| 933 |
-
st.dataframe(df, use_container_width=True)
|
| 934 |
-
|
| 935 |
-
st.caption("Client Center 연동형 상태변화기록지 생성기")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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