devorah-ai-2016 commited on
Commit
adf6ad4
·
verified ·
1 Parent(s): 01547c7

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -886
app.py DELETED
@@ -1,886 +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 + 상담일지 + 욕구사정 연동형
19
- # =========================================================
20
-
21
- st.set_page_config(page_title="BeeCare 통합 사례관리", page_icon="📋", layout="wide")
22
-
23
- CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
24
-
25
- DB_CANDIDATES = [
26
- os.path.join(CURRENT_DIR, "data", "clients.db"),
27
- os.path.join(CURRENT_DIR, "..", "Client Center", "data", "clients.db"),
28
- os.path.join(CURRENT_DIR, "..", "ClientCenter", "data", "clients.db"),
29
- os.path.join(CURRENT_DIR, "..", "Client_Center", "data", "clients.db"),
30
- ]
31
-
32
- DB_PATH = None
33
- for p in DB_CANDIDATES:
34
- if os.path.exists(p):
35
- DB_PATH = p
36
- break
37
-
38
- if DB_PATH is None:
39
- os.makedirs(os.path.join(CURRENT_DIR, "data"), exist_ok=True)
40
- DB_PATH = os.path.join(CURRENT_DIR, "data", "clients.db")
41
-
42
-
43
- # -----------------------------
44
- # UI 디자인
45
- # -----------------------------
46
- st.markdown("""
47
- <style>
48
- .block-container { padding-top: 2rem; }
49
- .hero {
50
- background: linear-gradient(135deg, #6D28D9, #9333EA);
51
- padding: 30px;
52
- border-radius: 22px;
53
- text-align: center;
54
- margin-bottom: 22px;
55
- }
56
- .hero h1 { color: white; margin: 0; font-size: 36px; }
57
- .hero p { color: white; margin-top: 10px; font-size: 18px; }
58
- .notice {
59
- background: #fff8e1;
60
- border-left: 7px solid #f9a825;
61
- padding: 15px;
62
- border-radius: 12px;
63
- margin-bottom: 18px;
64
- }
65
- .okbox {
66
- background: #e8f5e9;
67
- border-left: 7px solid #43a047;
68
- padding: 14px;
69
- border-radius: 12px;
70
- margin-bottom: 14px;
71
- }
72
- .warnbox {
73
- background: #fff3e0;
74
- border-left: 7px solid #fb8c00;
75
- padding: 14px;
76
- border-radius: 12px;
77
- margin-bottom: 14px;
78
- }
79
- </style>
80
- """, unsafe_allow_html=True)
81
-
82
- st.markdown("""
83
- <div class="hero">
84
- <h1>📋 BeeCare 통합 사례관리 생성기</h1>
85
- <p>수급자 정보, 상담일지, 욕구사정 내용을 연결하여 1차 계획회의록과 2차 결과회의록을 생성합니다.</p>
86
- </div>
87
- """, unsafe_allow_html=True)
88
-
89
- st.markdown("""
90
- <div class="notice">
91
- <strong>연동 구조:</strong> Client Center 수급자 DB → 상담기록 → 욕구사정 요약 → 사례관리 1차 계획 → 역할별 시행과정 → 2차 결과평가
92
- </div>
93
- """, unsafe_allow_html=True)
94
-
95
-
96
- # -----------------------------
97
- # DB
98
- # -----------------------------
99
- def get_conn():
100
- return sqlite3.connect(DB_PATH, check_same_thread=False)
101
-
102
-
103
- def init_db():
104
- conn = get_conn()
105
- cur = conn.cursor()
106
-
107
- cur.execute("""
108
- CREATE TABLE IF NOT EXISTS clients (
109
- id INTEGER PRIMARY KEY AUTOINCREMENT,
110
- name TEXT NOT NULL,
111
- masked_name TEXT,
112
- gender TEXT,
113
- birth_year TEXT,
114
- care_grade TEXT,
115
- institution_type TEXT,
116
- institution_name TEXT,
117
- admission_date TEXT,
118
- main_condition TEXT,
119
- cognitive_status TEXT,
120
- mobility_status TEXT,
121
- diet_status TEXT,
122
- toileting_status TEXT,
123
- guardian_name TEXT,
124
- guardian_phone TEXT,
125
- notes TEXT,
126
- status TEXT DEFAULT '이용중',
127
- created_at TEXT,
128
- updated_at TEXT
129
- )
130
- """)
131
-
132
- cur.execute("""
133
- CREATE TABLE IF NOT EXISTS counseling_records (
134
- id INTEGER PRIMARY KEY AUTOINCREMENT,
135
- client_id INTEGER,
136
- client_masked_name TEXT,
137
- institution_type TEXT,
138
- counseling_type TEXT,
139
- counseling_date TEXT,
140
- counselor TEXT,
141
- counseling_reason TEXT,
142
- client_status_change TEXT,
143
- guardian_opinion TEXT,
144
- counseling_content TEXT,
145
- action_plan TEXT,
146
- evaluation_score INTEGER,
147
- missing_items TEXT,
148
- compliance_result TEXT,
149
- next_due_note TEXT,
150
- created_at TEXT
151
- )
152
- """)
153
-
154
- # 욕구사정 생성기가 나중에 저장 기능을 붙이면 이 테이블을 그대로 사용 가능
155
- cur.execute("""
156
- CREATE TABLE IF NOT EXISTS needs_assessment_records (
157
- id INTEGER PRIMARY KEY AUTOINCREMENT,
158
- client_id INTEGER,
159
- client_masked_name TEXT,
160
- assessment_date TEXT,
161
- total_opinion TEXT,
162
- result_status TEXT,
163
- result_plan TEXT,
164
- fall_risk TEXT,
165
- bedsore_risk TEXT,
166
- dementia_status TEXT,
167
- diaper_use TEXT,
168
- service_needs TEXT,
169
- created_at TEXT
170
- )
171
- """)
172
-
173
- cur.execute("""
174
- CREATE TABLE IF NOT EXISTS case_management_records (
175
- id INTEGER PRIMARY KEY AUTOINCREMENT,
176
- client_id INTEGER,
177
- client_masked_name TEXT,
178
- institution_type TEXT,
179
- case_type TEXT,
180
- first_meeting_date TEXT,
181
- second_meeting_date TEXT,
182
- selection_reason TEXT,
183
- first_plan TEXT,
184
- implementation_process TEXT,
185
- second_result TEXT,
186
- evaluation_score INTEGER,
187
- missing_items TEXT,
188
- created_at TEXT
189
- )
190
- """)
191
-
192
- conn.commit()
193
- conn.close()
194
-
195
-
196
- def load_clients():
197
- conn = get_conn()
198
- try:
199
- df = pd.read_sql_query("""
200
- SELECT * FROM clients ORDER BY id DESC
201
- """, conn)
202
- except Exception:
203
- df = pd.DataFrame()
204
- conn.close()
205
- return df
206
-
207
-
208
- def load_counseling(client_id):
209
- conn = get_conn()
210
- try:
211
- df = pd.read_sql_query("""
212
- SELECT * FROM counseling_records
213
- WHERE client_id = ?
214
- ORDER BY counseling_date DESC, id DESC
215
- """, conn, params=(int(client_id),))
216
- except Exception:
217
- df = pd.DataFrame()
218
- conn.close()
219
- return df
220
-
221
-
222
- def load_needs_assessment(client_id):
223
- conn = get_conn()
224
- try:
225
- df = pd.read_sql_query("""
226
- SELECT * FROM needs_assessment_records
227
- WHERE client_id = ?
228
- ORDER BY assessment_date DESC, id DESC
229
- """, conn, params=(int(client_id),))
230
- except Exception:
231
- df = pd.DataFrame()
232
- conn.close()
233
- return df
234
-
235
-
236
- def save_case_record(data):
237
- conn = get_conn()
238
- cur = conn.cursor()
239
- cur.execute("""
240
- INSERT INTO case_management_records (
241
- client_id, client_masked_name, institution_type, case_type,
242
- first_meeting_date, second_meeting_date, selection_reason,
243
- first_plan, implementation_process, second_result,
244
- evaluation_score, missing_items, created_at
245
- )
246
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
247
- """, (
248
- data["client_id"], data["client_masked_name"], data["institution_type"], data["case_type"],
249
- data["first_meeting_date"], data["second_meeting_date"], data["selection_reason"],
250
- data["first_plan"], data["implementation_process"], data["second_result"],
251
- data["evaluation_score"], data["missing_items"],
252
- datetime.now().strftime("%Y-%m-%d %H:%M:%S")
253
- ))
254
- conn.commit()
255
- conn.close()
256
-
257
-
258
- def safe(row, key, default=""):
259
- try:
260
- v = row.get(key, default)
261
- if pd.isna(v):
262
- return default
263
- return str(v)
264
- except Exception:
265
- return default
266
-
267
-
268
- def mask_name(name):
269
- name = str(name or "").strip()
270
- if len(name) >= 3:
271
- return name[0] + "○" + name[2:]
272
- if len(name) == 2:
273
- return name[0] + "○"
274
- return name
275
-
276
-
277
- init_db()
278
-
279
-
280
- # -----------------------------
281
- # 사례 유형
282
- # -----------------------------
283
- CASE_TYPES = {
284
- "낙상 고위험 관리": {
285
- "reason": "이동 중 불안정, 화장실 이동 위험, 보행보조 필요 등 낙상 위험요인이 확인되어 사례관리가 필요함.",
286
- "goal": "낙상 사고를 예방하고 안전한 이동과 생활환경을 유지한다.",
287
- "keywords": ["낙상예방", "이동보조", "환경정비", "화장실 동행", "보행상태 관찰"],
288
- },
289
- "식사량 감소·영양관리": {
290
- "reason": "식사량 감소, 수분섭취 부족, 체중저하 우려가 확인되어 영양상태 관리를 위한 사례관리가 필요함.",
291
- "goal": "식사량과 수분섭취를 안정적으로 유지하고 영양 저하 위험을 예방한다.",
292
- "keywords": ["식사보조", "수분섭취", "선호음식", "연하상태", "섭취량 기록"],
293
- },
294
- "인지저하·정서불안": {
295
- "reason": "반복질문, 의심표현, 불안감, 정서적 위축 등 인지·정서 변화가 확인되어 지속 관찰과 개별 대응이 필요함.",
296
- "goal": "불안감을 완화하고 안정적인 일상생활과 서비스 이용이 이루어지도록 지원한다.",
297
- "keywords": ["정서지원", "인지활동", "반복설명", "안정적 환경", "보호자 상담"],
298
- },
299
- "욕창·피부상태 관리": {
300
- "reason": "기저귀 착용, 활동량 저하, 피부 발적 또는 욕창 위험이 확인되어 피부상태 관찰과 예방관리가 필요함.",
301
- "goal": "피부 청결과 안위를 유지하고 욕창 발생을 예방한다.",
302
- "keywords": ["피부관찰", "체위변경", "기저귀케어", "보습", "간호관찰"],
303
- },
304
- "프로그램 참여 저하": {
305
- "reason": "프로그램 참여 감소, 무기력, 대화 회피 등 사회적·정서적 위축이 관찰되어 사례관리가 필요함.",
306
- "goal": "선호 활동 중심으로 참여를 유도하고 사회적 관계와 활력��� 높인다.",
307
- "keywords": ["선호활동", "참여격려", "정서지원", "프로그램 조정", "참여도 기록"],
308
- },
309
- "보호자 요청·서비스 조정": {
310
- "reason": "보호자 요청 또는 서비스 조정 필요성이 확인되어 급여제공 방향 재검토와 사례관리가 필요함.",
311
- "goal": "보호자 의견과 수급자 상태를 반영하여 적절한 서비스 제공 방향을 조정한다.",
312
- "keywords": ["보호자 상담", "서비스 조정", "급여계획 반영", "종사자 공유", "후속상담"],
313
- },
314
- }
315
-
316
-
317
- OPENERS = [
318
- "회의 참석자들은 최근 상담기록과 욕구사정 내용을 함께 검토하였다.",
319
- "본 사례회의에서는 수급자의 상태 변화, 보호자 의견, 급여제공 중 관찰사항을 종합하였다.",
320
- "금일 회의에서는 단순 문제기록이 아니라 실제 서비스 제공 과정에 반영할 개입 방향을 중심으로 논의하였다.",
321
- "수급자의 욕구와 기관에서 제공 가능한 자원을 연결하여 사례관리 필요성을 검토하였다.",
322
- ]
323
-
324
- TONES = [
325
- "각 직종별 역할을 명확히 하여 동일한 방향으로 지원하기로 하였다.",
326
- "상담기록, 욕구사정, 급여제공기록이 서로 연결되도록 관리하기로 하였다.",
327
- "보호자에게도 주요 변화와 기관의 조치계획을 안내하여 협조를 구하기로 하였다.",
328
- "30일 이상 관찰 후 결과를 다시 확인하고 필요 시 급여제공계획을 조정하기로 하였다.",
329
- ]
330
-
331
-
332
- # -----------------------------
333
- # 요약 생성
334
- # -----------------------------
335
- def summarize_counseling(df):
336
- if df.empty:
337
- return "저장된 상담일지가 없어 수급자 기본정보와 직접 입력한 상태변화를 중심으로 사례관리 회의를 진행함."
338
- lines = []
339
- for _, r in df.head(5).iterrows():
340
- lines.append(
341
- f"- {safe(r,'counseling_date')}: {safe(r,'counseling_type')} / 사유: {safe(r,'counseling_reason')} / "
342
- f"상태변화: {safe(r,'client_status_change') or '기록 없음'} / 보호자 의견: {safe(r,'guardian_opinion') or '기록 없음'}"
343
- )
344
- return "\n".join(lines)
345
-
346
-
347
- def summarize_needs(df, client, manual_needs):
348
- if not df.empty:
349
- r = df.iloc[0]
350
- return (
351
- f"최근 욕구사정일: {safe(r,'assessment_date')}\n"
352
- f"종합소견: {safe(r,'total_opinion')}\n"
353
- f"결과/계획: {safe(r,'result_plan')}\n"
354
- f"위험요인: 낙상 {safe(r,'fall_risk')}, 욕창 {safe(r,'bedsore_risk')}, 인지 {safe(r,'dementia_status')}, 기저귀 {safe(r,'diaper_use')}\n"
355
- f"서비스 욕구: {safe(r,'service_needs')}"
356
- )
357
-
358
- base = (
359
- f"Client Center 등록정보 기준 주요상태: {safe(client,'main_condition') or '기록 없음'}, "
360
- f"인지상태: {safe(client,'cognitive_status') or '기록 없음'}, "
361
- f"이동상태: {safe(client,'mobility_status') or '기록 없음'}, "
362
- f"식사상태: {safe(client,'diet_status') or '기록 없음'}, "
363
- f"배변/배뇨상태: {safe(client,'toileting_status') or '기록 없음'}"
364
- )
365
- if manual_needs.strip():
366
- base += "\n직접 입력 욕구사정 요약: " + manual_needs.strip()
367
- return base
368
-
369
-
370
- def build_role_text(case_type, custom_roles=""):
371
- keywords = ", ".join(CASE_TYPES[case_type]["keywords"])
372
- default = f"""
373
- 시설장: 사례관리 대상 선정의 적절성을 확인하고, 민원·안전·급여제공 반영 여부를 총괄 점검한다.
374
- 사회복지사: 상담기록과 욕구사정 내용을 분석하여 사례관리 목표와 계획을 수립하고 보호자 상담 및 급여제공계획 반영을 담당한다.
375
- 요양보호사: 일상 서비스 제공 과정에서 {keywords} 관련 관찰사항을 구체적으로 기록하고 즉시 공유한다.
376
- 간호조무사: 건강상태, 활력징후, 피부상태, 복약 및 이상징후를 관찰하고 필요 시 의료연계 필요성을 보고한다.
377
- 물리치료사: 이동, 자세유지, 보행, 관절구축 예방과 관련된 신체기능 지원 방향을 자문한다.
378
- """.strip()
379
- return custom_roles.strip() or default
380
-
381
-
382
- def build_attendees_text(director, social_worker, caregiver, nurse, therapist, guardian, extra_attendees):
383
- attendees = []
384
- if director.strip():
385
- attendees.append(f"시설장: {director.strip()}")
386
- else:
387
- attendees.append("시설장: 참석 또는 검토")
388
- if social_worker.strip():
389
- attendees.append(f"사회복지사: {social_worker.strip()}")
390
- else:
391
- attendees.append("사회복지사: 참석")
392
- if caregiver.strip():
393
- attendees.append(f"요양보호사: {caregiver.strip()}")
394
- else:
395
- attendees.append("요양보호사: 참석")
396
- if nurse.strip():
397
- attendees.append(f"간호조무사: {nurse.strip()}")
398
- else:
399
- attendees.append("간호조무사: 참석")
400
- if therapist.strip():
401
- attendees.append(f"물리치료사: {therapist.strip()}")
402
- else:
403
- attendees.append("물리치료사: 해당 시 자문")
404
- if guardian.strip():
405
- attendees.append(f"보호자: {guardian.strip()}")
406
- if extra_attendees.strip():
407
- attendees.append(f"기타 참석자: {extra_attendees.strip()}")
408
- return "\n".join(attendees)
409
-
410
-
411
- def build_case_documents(client, counseling_summary, needs_summary, case_type, custom_selection, custom_status, custom_goal, custom_roles):
412
- case = CASE_TYPES[case_type]
413
- opener = random.choice(OPENERS)
414
- tone = random.choice(TONES)
415
- masked = safe(client, "masked_name", "수급자")
416
- grade = safe(client, "care_grade")
417
- institution_type = safe(client, "institution_type")
418
- keywords = ", ".join(case["keywords"])
419
-
420
- selection = custom_selection.strip() or (
421
- f"{masked} 수급자는 {grade} 대상자로 {case['reason']} "
422
- f"상담기록과 욕구사정에서 확인된 상태를 종합할 때 {case_type} 사례관리 대상으로 선정함."
423
- )
424
-
425
- first_content = f"""
426
- {opener}
427
-
428
- [수급자 기본상태]
429
- - 기관유형: {institution_type}
430
- - 장기요양등급: {grade}
431
- - 주요 질환/상태: {safe(client,'main_condition') or '기록 없음'}
432
- - 인지상태: {safe(client,'cognitive_status') or '기록 없음'}
433
- - 이동상태: {safe(client,'mobility_status') or '기록 없음'}
434
- - 식사상태: {safe(client,'diet_status') or '기록 없음'}
435
- - 배변/배뇨상태: {safe(client,'toileting_status') or '기록 없음'}
436
-
437
- [상담일지 연동 요약]
438
- {counseling_summary}
439
-
440
- [욕구사정 연동 요약]
441
- {needs_summary}
442
-
443
- [추가 상태변화]
444
- {custom_status or '추가로 입력된 상태변화는 없으나, 기존 기록을 바탕으로 지속 관찰이 필요함.'}
445
-
446
- 회의 결과 {case_type}과 관련하여 {keywords} 항목을 중심으로 개입하기로 하였으며, {tone}
447
- """.strip()
448
-
449
- goal = custom_goal.strip() or case["goal"]
450
-
451
- plan = f"""
452
- [1차 사례관리 목표]
453
- {goal}
454
-
455
- [1차 사례관리 계획]
456
- 1. 상담일지와 욕구사정에서 확인된 위험요인 및 욕구를 급여제공계획에 반영한다.
457
- 2. {keywords} 관련 관찰 항목을 급여제공기록지에 구체적으로 남긴다.
458
- 3. 보호자 의견 또는 상태변화가 확인될 경우 즉시 사회복지사에게 공유한다.
459
- 4. 시설장 확인 하에 30일 이상 시행과정을 점검하고 2차 결과회의에서 효과성을 평가한다.
460
- 5. 필요 시 추가 상담, 욕구사정 재점검, 급여제공계획 변경으로 연계한다.
461
- """.strip()
462
-
463
- role_division = build_role_text(case_type, custom_roles)
464
-
465
- implementation = f"""
466
- [역할분담에 따른 시행과정]
467
- - 시설장: 사례관리 진행상황과 기록 적정성을 확인하고, 급여제공계획 반영 여부를 점검하였다.
468
- - 사회복지사: 상담일지와 욕구사정 내용을 통합 검토하여 보호자 의견, 상태변화, 서비스 조정 필요성을 급여제공계획에 연결하였다.
469
- - 요양보호사: 실제 급여제공 과정에서 {keywords} 관련 관찰사항을 확인하고 일상기록에 반영하였다.
470
- - 간호조무사: 건강상태, 피부상태, 식사·수분섭취, 활력상태 등 위험요인을 확인하고 이상징후 발생 여부를 관찰하였다.
471
- - 물리치료사: 이동, 자세, 관절구축 예방, 신체활동 지원 필요성을 검토하고 현장 적용 가능한 지원 방향을 제안하였다.
472
-
473
- [과정 점검]
474
- 상담기록과 욕구사정에서 확인된 내용이 실제 서비스 제공 과정에서 누락되지 않도록 종사자 간 공유하였으며, 수급자의 반응과 보호자 의견을 지속 확인하였다.
475
- """.strip()
476
-
477
- second_result = f"""
478
- [2차 결과회의 내용]
479
- 30일 이상 시행과정을 확인한 결과, {case_type} 관련 위험요인과 욕구에 대해 역할별 지원이 이루어졌는지 점검하였다.
480
-
481
- [결과평가]
482
- - 수급자 상태변화: 상담기록 및 관찰기록을 통해 변화 여부를 확인함.
483
- - 보호자 의견 반영: 보호자 의견이 있는 경우 급여제공 방향과 후속조치에 반영함.
484
- - 급여제공 반영: 1차 계획에서 정한 {keywords} 항목을 급여제공기록과 서비스 제공 과정에 반영함.
485
- - 향후계획: 현재 계획을 유지하되, 상태 악화나 새로운 욕구 발생 시 욕구사정 재점검 및 급여제공계획 변경을 검토함.
486
- """.strip()
487
-
488
- return selection, first_content, goal, plan, role_division, implementation, second_result
489
-
490
-
491
- def evaluate_case(selection, first_content, plan, role_division, implementation, second_result, counseling_summary, needs_summary):
492
- required = {
493
- "선정사유": bool(selection.strip()),
494
- "상담일지 연동": "상담" in counseling_summary and "저장된 상담일지 없어" not in counseling_summary,
495
- "욕구사정 연동": bool(needs_summary.strip()),
496
- "1차 계획": bool(plan.strip()) and "목표" in plan,
497
- "역할분담": all(word in role_division for word in ["시설장", "사회복지사", "요양보호사", "간호조무사", "물리치료사"]),
498
- "시행과정": bool(implementation.strip()) and "시행과정" in implementation,
499
- "2차 결과회의": bool(second_result.strip()) and "결과" in second_result,
500
- "보호자 의견/상태변화": ("보호자" in first_content or "보호자" in second_result) and ("상태변화" in first_content or "변화" in second_result),
501
- "급여제공 반영": "급여제공" in plan and "급여제공" in second_result,
502
- }
503
- score = int(sum(required.values()) / len(required) * 100)
504
- missing = [k for k, v in required.items() if not v]
505
- if score >= 90:
506
- result = "평가 적합도가 높습니다. 사례선정, 1차 계획, 역할분담, 시행과정, 2차 결과평가가 연결되어 있습니다."
507
- elif score >= 75:
508
- result = "대체로 적합하나 일부 보완이 필요합니다. 부족 항목을 추가하면 평가 대응력이 높아집니다."
509
- else:
510
- result = "보완이 필요합니다. 상담일지, 욕구사정, 역할별 시행과정, 2차 결과평가가 더 구체적으로 연결되어야 합니다."
511
- return score, missing, result
512
-
513
-
514
- # -----------------------------
515
- # 엑셀 함수
516
- # -----------------------------
517
- def set_cell(ws, cell, value, bold=False, size=11, fill=None, align="center"):
518
- ws[cell] = value
519
- ws[cell].font = Font(name="Malgun Gothic", size=size, bold=bold)
520
- ws[cell].alignment = Alignment(horizontal=align, vertical="center", wrap_text=True)
521
- if fill:
522
- ws[cell].fill = fill
523
-
524
-
525
- def style_ws(ws, max_row):
526
- thin = Side(style="thin", color="777777")
527
- border = Border(left=thin, right=thin, top=thin, bottom=thin)
528
- for row in ws.iter_rows(min_row=1, max_row=max_row, min_col=1, max_col=9):
529
- for cell in row:
530
- if cell.value is not None:
531
- cell.border = border
532
- if cell.font.name != "Malgun Gothic":
533
- cell.font = Font(name="Malgun Gothic", size=11, bold=cell.font.bold)
534
- ws.page_setup.paperSize = ws.PAPERSIZE_A4
535
- ws.page_setup.orientation = "portrait"
536
- ws.page_setup.fitToWidth = 1
537
- ws.page_setup.fitToHeight = 0
538
- ws.sheet_properties.pageSetUpPr.fitToPage = True
539
- ws.page_margins.left = 0.3
540
- ws.page_margins.right = 0.3
541
- ws.page_margins.top = 0.4
542
- ws.page_margins.bottom = 0.4
543
- ws.sheet_view.showGridLines = False
544
-
545
-
546
- def write_title_with_approval(ws, title, title_fill, header_fill):
547
- for col in range(1, 10):
548
- ws.column_dimensions[get_column_letter(col)].width = 15
549
-
550
- ws.merge_cells(start_row=1, start_column=1, end_row=2, end_column=7)
551
- ws.cell(1, 1).value = title
552
- ws.cell(1, 1).font = Font(name="Malgun Gothic", size=24, bold=True)
553
- ws.cell(1, 1).alignment = Alignment(horizontal="center", vertical="center")
554
- ws.cell(1, 1).fill = title_fill
555
-
556
- # 결재라인: H:I 두 칸만 사용, 지저분한 G열/빈칸 없음
557
- ws.cell(1, 8).value = "담당자"
558
- ws.cell(1, 9).value = "시설장"
559
- ws.cell(2, 8).value = ""
560
- ws.cell(2, 9).value = ""
561
- for rr in [1, 2]:
562
- for cc in [8, 9]:
563
- cell = ws.cell(rr, cc)
564
- cell.font = Font(name="Malgun Gothic", size=11, bold=True if rr == 1 else False)
565
- cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
566
- if rr == 1:
567
- cell.fill = header_fill
568
- ws.row_dimensions[1].height = 28
569
- ws.row_dimensions[2].height = 42
570
-
571
-
572
- def write_info_row(ws, row, a, b, c, d, e, f, header_fill):
573
- ws.cell(row, 1).value = a
574
- ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=3)
575
- ws.cell(row, 2).value = b
576
- ws.cell(row, 4).value = c
577
- ws.merge_cells(start_row=row, start_column=5, end_row=row, end_column=6)
578
- ws.cell(row, 5).value = d
579
- ws.cell(row, 7).value = e
580
- ws.merge_cells(start_row=row, start_column=8, end_row=row, end_column=9)
581
- ws.cell(row, 8).value = f
582
-
583
- for col in [1, 4, 7]:
584
- ws.cell(row, col).fill = header_fill
585
- ws.cell(row, col).font = Font(name="Malgun Gothic", size=11, bold=True)
586
- ws.cell(row, col).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
587
- for col in [2, 5, 8]:
588
- ws.cell(row, col).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
589
- ws.row_dimensions[row].height = 30
590
-
591
-
592
- def write_section(ws, row, title, content, header_fill, height=90):
593
- ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
594
- ws.cell(row, 1).value = title
595
- ws.cell(row, 1).font = Font(name="Malgun Gothic", size=15, bold=True)
596
- ws.cell(row, 1).alignment = Alignment(horizontal="center", vertical="center")
597
- ws.cell(row, 1).fill = header_fill
598
- ws.row_dimensions[row].height = 30
599
- row += 1
600
-
601
- ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
602
- ws.cell(row, 1).value = content
603
- ws.cell(row, 1).font = Font(name="Malgun Gothic", size=11)
604
- ws.cell(row, 1).alignment = Alignment(horizontal="left", vertical="top", wrap_text=True)
605
- lines = len(str(content)) // 60 + 1 + str(content).count("\n")
606
- ws.row_dimensions[row].height = max(height, lines * 18)
607
- return row + 1
608
-
609
-
610
- def generate_excel(data):
611
- wb = Workbook()
612
- title_fill = PatternFill("solid", fgColor="EDE9FE")
613
- header_fill = PatternFill("solid", fgColor="F3F4F6")
614
-
615
- ws1 = wb.active
616
- ws1.title = "1차계획회의록"
617
- write_title_with_approval(ws1, "사례관리 1차 계획회의록", title_fill, header_fill)
618
-
619
- r = 3
620
- write_info_row(ws1, r, "기관명", data["institution_name"], "기관유형", data["institution_type"], "회의일자", data["first_meeting_date"], header_fill); r += 1
621
- write_info_row(ws1, r, "수급자", data["client_masked_name"], "장기요양등급", data["grade"], "사례유형", data["case_type"], header_fill); r += 1
622
- write_info_row(ws1, r, "회의장소", data["meeting_place"], "작성자", data["writer"], "2차예정일", data["second_meeting_date"], header_fill); r += 1
623
- r = write_section(ws1, r, "선정사유", data["selection_reason"], header_fill, 80)
624
- r = write_section(ws1, r, "상담일지 연동 요약", data["counseling_summary"], header_fill, 90)
625
- r = write_section(ws1, r, "욕구사정 연동 요약", data["needs_summary"], header_fill, 90)
626
- r = write_section(ws1, r, "1차 회의내용", data["first_content"], header_fill, 150)
627
- r = write_section(ws1, r, "1차 사례관리 목표 및 계획", f"[목표]\n{data['goal']}\n\n[계획]\n{data['first_plan']}", header_fill, 140)
628
- r = write_section(ws1, r, "역할분담", data["role_division"], header_fill, 130)
629
- r = write_section(ws1, r, "참석자 명단", data.get("attendees_text", "시설장, 사회복지사, 요양보호사, 간호조무사 참석"), header_fill, 90)
630
- r = write_section(ws1, r, "평가 적합도 점검", f"{data['evaluation_score']}점\n부족 항목: {data['missing_items']}\n{data['compliance_result']}", header_fill, 80)
631
-
632
- # 사진첨부: 업로드된 사진이 있을 때만 깔끔하게 삽입
633
- if data.get("photo_paths"):
634
- ws1.merge_cells(start_row=r, start_column=1, end_row=r, end_column=9)
635
- ws1.cell(r, 1).value = "사진첨부"
636
- ws1.cell(r, 1).font = Font(name="Malgun Gothic", size=15, bold=True)
637
- ws1.cell(r, 1).alignment = Alignment(horizontal="center", vertical="center")
638
- ws1.cell(r, 1).fill = header_fill
639
- r += 1
640
-
641
- img_row = r
642
- anchors = ["A", "D", "G"]
643
- for idx, photo_path in enumerate(data.get("photo_paths", [])[:3]):
644
- try:
645
- img = XLImage(photo_path)
646
- img.width = 210
647
- img.height = 150
648
- ws1.add_image(img, f"{anchors[idx]}{img_row}")
649
- except Exception:
650
- pass
651
- for rr in range(img_row, img_row + 8):
652
- ws1.row_dimensions[rr].height = 22
653
- r = img_row + 8
654
-
655
- style_ws(ws1, r)
656
-
657
- ws2 = wb.create_sheet("2차결과회의록")
658
- write_title_with_approval(ws2, "사례관리 2차 결과회의록", title_fill, header_fill)
659
-
660
- r = 3
661
- write_info_row(ws2, r, "수급자", data["client_masked_name"], "1차회의일", data["first_meeting_date"], "2차회의일", data["second_meeting_date"], header_fill); r += 1
662
- write_info_row(ws2, r, "관찰기간", data["observation_period"], "평가결과", data["result_level"], "작성자", data["writer"], header_fill); r += 1
663
- r = write_section(ws2, r, "참석자 명단", data.get("attendees_text", "시설장, 사회복지사, 요양보호사, 간호조무사 참석"), header_fill, 90)
664
- r = write_section(ws2, r, "역할분담에 따른 시행과정", data["implementation_process"], header_fill, 170)
665
- r = write_section(ws2, r, "2차 결과회의록", data["second_result"], header_fill, 160)
666
- r = write_section(ws2, r, "향후 급여제공 반영계획", data["next_plan"], header_fill, 110)
667
- r = write_section(ws2, r, "평가 적합도 점검", f"{data['evaluation_score']}점\n부족 항목: {data['missing_items']}\n{data['compliance_result']}", header_fill, 80)
668
- style_ws(ws2, r)
669
-
670
- output = BytesIO()
671
- wb.save(output)
672
- output.seek(0)
673
- return output
674
-
675
-
676
- # -----------------------------
677
- # 화면
678
- # -----------------------------
679
- st.sidebar.success("DB 연결")
680
- st.sidebar.caption(DB_PATH)
681
-
682
- clients_df = load_clients()
683
- if clients_df.empty:
684
- st.warning("Client Center 수급자 DB가 비어 있습니다. 직접 입력 모드로 임시 생성합니다.")
685
- temp_name = st.text_input("수급자명", "홍길동")
686
- client = pd.Series({
687
- "id": 0, "name": temp_name, "masked_name": mask_name(temp_name), "care_grade": "3등급",
688
- "institution_type": "방문요양", "institution_name": "", "main_condition": "",
689
- "cognitive_status": "", "mobility_status": "", "diet_status": "", "toileting_status": ""
690
- })
691
- else:
692
- options = clients_df.apply(lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_type']} / {x.get('status','')}", axis=1).tolist()
693
- selected_option = st.selectbox("수급자 선택", options)
694
- selected_id = int(selected_option.split("번")[0])
695
- client = clients_df[clients_df["id"] == selected_id].iloc[0]
696
-
697
- client_id = int(safe(client, "id", 0) or 0)
698
- counseling_df = load_counseling(client_id)
699
- needs_df = load_needs_assessment(client_id)
700
-
701
- c1, c2, c3, c4 = st.columns(4)
702
- c1.metric("수급자", safe(client, "masked_name"))
703
- c2.metric("등급", safe(client, "care_grade"))
704
- c3.metric("기관유형", safe(client, "institution_type"))
705
- c4.metric("상담기록", f"{len(counseling_df)}건")
706
-
707
- st.markdown("### 연동 자료 확인")
708
- with st.expander("상담일지 연동 내용", expanded=True):
709
- if counseling_df.empty:
710
- st.info("저장된 상담기록이 없습니다. 상담일지 생성기에서 먼저 저장하면 자동 연동됩니다.")
711
- else:
712
- st.dataframe(counseling_df[["counseling_date", "counseling_type", "counseling_reason", "client_status_change", "guardian_opinion"]], use_container_width=True)
713
-
714
- with st.expander("욕구사정 연동 내용", expanded=True):
715
- if needs_df.empty:
716
- st.info("저장된 욕구사정 기록이 없습니다. 아래 직접 입력 요약을 사용하거나, 욕구사정 생성기에 저장 기능을 추가하면 자동 연동됩니다.")
717
- else:
718
- st.dataframe(needs_df, use_container_width=True)
719
-
720
- manual_needs_summary = st.text_area(
721
- "욕구사정 요약 직접 입력",
722
- placeholder="예: 낙상위험 높음, 인지저하 의심, 식사량 감소, 배변관리 필요, 정서지원 필요 등",
723
- height=90,
724
- )
725
-
726
- st.markdown("### 사례관리 기본 입력")
727
- col1, col2, col3 = st.columns(3)
728
- institution_name = col1.text_input("기관명", value=safe(client, "institution_name"))
729
- institution_type = col2.selectbox(
730
- "기관유형",
731
- ["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"],
732
- index=["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"].index(safe(client, "institution_type")) if safe(client, "institution_type") in ["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"] else 0
733
- )
734
- case_type = col3.selectbox("사례관리 유형", list(CASE_TYPES.keys()))
735
-
736
- col4, col5, col6 = st.columns(3)
737
- first_meeting_date = col4.date_input("1차 회의일", value=date.today())
738
- second_meeting_date = col5.date_input("2차 결과회의일", value=date.today() + timedelta(days=30))
739
- writer = col6.text_input("작성자", "사회복지사")
740
-
741
- meeting_place = st.text_input("회의장소", "기관 내 상담실")
742
- observation_period = st.text_input("관찰기간", f"{first_meeting_date} ~ {second_meeting_date}")
743
- result_level = st.selectbox("2차 평가결과", ["목표달성", "부분달성", "진행중", "미달성", "지속관찰"])
744
-
745
- custom_selection = st.text_area("선정사유 보완 입력", height=80)
746
- custom_status = st.text_area("상태변화 / 보호자 의견 / 추가 관찰내용", height=100)
747
- custom_goal = st.text_area("사례관리 목표 직접 입력", height=70)
748
- custom_roles = st.text_area("역할분담 직접 수정", height=120)
749
-
750
- st.markdown("### 참석자 명단")
751
- a1, a2, a3 = st.columns(3)
752
- director_name = a1.text_input("시설장", "")
753
- social_worker_name = a2.text_input("사회복지사", "")
754
- caregiver_name = a3.text_input("요양보호사", "")
755
-
756
- a4, a5, a6 = st.columns(3)
757
- nurse_name = a4.text_input("간호조무사", "")
758
- therapist_name = a5.text_input("물리치료사", "")
759
- guardian_name = a6.text_input("보호자", "")
760
-
761
- extra_attendees = st.text_input("기타 참석자", "")
762
-
763
- st.markdown("### 사진첨부")
764
- case_photos = st.file_uploader(
765
- "사례관리 관련 사진 첨부 (최대 3장, 선택사항)",
766
- type=["png", "jpg", "jpeg"],
767
- accept_multiple_files=True
768
- )
769
-
770
- def save_uploaded_photos(uploaded_files):
771
- paths = []
772
- for file in (uploaded_files or [])[:3]:
773
- suffix = os.path.splitext(file.name)[1].lower() or ".png"
774
- temp_path = os.path.join(tempfile.gettempdir(), f"case_photo_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{suffix}")
775
- with open(temp_path, "wb") as f:
776
- f.write(file.getbuffer())
777
- paths.append(temp_path)
778
- return paths
779
-
780
- if st.button("📋 사례관리 1차/2차 회의록 생성", use_container_width=True):
781
- counseling_summary = summarize_counseling(counseling_df)
782
- needs_summary = summarize_needs(needs_df, client, manual_needs_summary)
783
-
784
- selection, first_content, goal, first_plan, role_division, implementation, second_result = build_case_documents(
785
- client, counseling_summary, needs_summary, case_type, custom_selection, custom_status, custom_goal, custom_roles
786
- )
787
-
788
- score, missing, compliance = evaluate_case(
789
- selection, first_content, first_plan, role_division, implementation, second_result, counseling_summary, needs_summary
790
- )
791
-
792
- next_plan = (
793
- "사례관리 결과를 급여제공계획서와 급여���공기록지에 반영하고, 상태 변화가 지속되거나 새로운 욕구가 확인될 경우 "
794
- "보호자 상담 및 욕구사정 재점검을 실시한다."
795
- )
796
-
797
- attendees_text = build_attendees_text(
798
- director_name, social_worker_name, caregiver_name,
799
- nurse_name, therapist_name, guardian_name, extra_attendees
800
- )
801
- photo_paths = save_uploaded_photos(case_photos)
802
-
803
- st.session_state["case_data"] = {
804
- "client_id": client_id,
805
- "client_masked_name": safe(client, "masked_name"),
806
- "institution_name": institution_name,
807
- "institution_type": institution_type,
808
- "grade": safe(client, "care_grade"),
809
- "case_type": case_type,
810
- "first_meeting_date": str(first_meeting_date),
811
- "second_meeting_date": str(second_meeting_date),
812
- "meeting_place": meeting_place,
813
- "writer": writer,
814
- "observation_period": observation_period,
815
- "result_level": result_level,
816
- "selection_reason": selection,
817
- "counseling_summary": counseling_summary,
818
- "needs_summary": needs_summary,
819
- "first_content": first_content,
820
- "goal": goal,
821
- "first_plan": first_plan,
822
- "role_division": role_division,
823
- "attendees_text": attendees_text,
824
- "photo_paths": photo_paths,
825
- "implementation_process": implementation,
826
- "second_result": second_result,
827
- "next_plan": next_plan,
828
- "evaluation_score": score,
829
- "missing_items": ", ".join(missing) if missing else "부족 항목 없음",
830
- "compliance_result": compliance,
831
- }
832
-
833
- if "case_data" in st.session_state:
834
- data = st.session_state["case_data"]
835
-
836
- st.markdown("---")
837
- st.subheader("생성 결과 수정")
838
-
839
- data["selection_reason"] = st.text_area("선정사유", value=data["selection_reason"], height=90)
840
- data["first_content"] = st.text_area("1차 회의내용", value=data["first_content"], height=220)
841
- data["first_plan"] = st.text_area("1차 계획", value=data["first_plan"], height=150)
842
- data["role_division"] = st.text_area("역할분담", value=data["role_division"], height=160)
843
- data["attendees_text"] = st.text_area("참석자 명단", value=data.get("attendees_text", ""), height=110)
844
- data["implementation_process"] = st.text_area("역할별 시행과정", value=data["implementation_process"], height=180)
845
- data["second_result"] = st.text_area("2차 결과회의록", value=data["second_result"], height=180)
846
- data["next_plan"] = st.text_area("향후계획", value=data["next_plan"], height=100)
847
-
848
- score, missing, compliance = evaluate_case(
849
- data["selection_reason"],
850
- data["first_content"],
851
- data["first_plan"],
852
- data["role_division"],
853
- data["implementation_process"],
854
- data["second_result"],
855
- data["counseling_summary"],
856
- data["needs_summary"],
857
- )
858
- data["evaluation_score"] = score
859
- data["missing_items"] = ", ".join(missing) if missing else "부족 항목 없음"
860
- data["compliance_result"] = compliance
861
-
862
- st.subheader("평가 적합도 점검")
863
- a, b, c = st.columns(3)
864
- a.metric("평가 적합도", f"{score}점")
865
- b.metric("부족 항목", data["missing_items"])
866
- c.metric("연동상태", "상담+욕구사정 반영")
867
-
868
- if score >= 90:
869
- st.markdown(f'<div class="okbox">{compliance}</div>', unsafe_allow_html=True)
870
- else:
871
- st.markdown(f'<div class="warnbox">{compliance}</div>', unsafe_allow_html=True)
872
-
873
- if st.button("💾 사례관리 기록 DB 저장", use_container_width=True):
874
- save_case_record(data)
875
- st.success("사례관리 기록이 저장되었습니다.")
876
-
877
- filename = f"사례관리_{data['client_masked_name']}_{datetime.now().strftime('%Y%m%d')}.xlsx"
878
- st.download_button(
879
- "📥 사례관리 1차/2차 회의록 엑셀 다운로드",
880
- data=generate_excel(data),
881
- file_name=filename,
882
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
883
- use_container_width=True,
884
- )
885
-
886
- st.caption("BeeCare Client Center + 상담일지 + 욕구사정 통합연동 사례관리 생성기")