devorah-ai-2016 commited on
Commit
755fb36
·
verified ·
1 Parent(s): 1cd3747

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1112
app.py DELETED
@@ -1,1112 +0,0 @@
1
- import os
2
- import re
3
- import sqlite3
4
- from io import BytesIO
5
- from datetime import datetime, date
6
-
7
- import pandas as pd
8
- import streamlit as st
9
- from openpyxl import load_workbook
10
- from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
11
- from openpyxl.worksheet.datavalidation import DataValidation
12
-
13
- CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
14
- if os.path.exists("/app/data/clients.db"):
15
- DB_PATH = "/app/data/clients.db"
16
- else:
17
- DB_DIR = os.path.join(CURRENT_DIR, "data")
18
- DB_PATH = os.path.join(DB_DIR, "clients.db")
19
- os.makedirs(DB_DIR, exist_ok=True)
20
-
21
- st.set_page_config(page_title="Client Center", page_icon="👥", layout="wide")
22
-
23
- # =========================================================
24
- # BeeCare Client Center Final
25
- # - 직접 등록 / 엑셀 업로드 / 검색 / 수정 / 삭제
26
- # - 인정번호 숫자 입력 시 L 자동 생성
27
- # - 인정기간 시작일/종료일 분리 저장
28
- # - 급여제공계획 작성기한 알림 기초 데이터 저장
29
- # - 다른 생성기와 같은 data/clients.db 사용
30
- # =========================================================
31
-
32
- VALID_GENDERS = ["여", "남", "기타"]
33
- VALID_GRADES = ["1등급", "2등급", "3등급", "4등급", "5등급", "인지지원등급", "등급외", "미입력"]
34
- VALID_INST_TYPES = ["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"]
35
- VALID_STATUS = ["이용중", "입소중", "퇴소", "중지", "사망"]
36
-
37
- EXCEL_COLUMNS = [
38
- "NO.", "수급자이름", "성별", "생년월일", "실질생일날짜", "장기요양등급", "인정번호",
39
- "인정기간시작일", "인정기간종료일", "입소일", "이용상태", "주요질환",
40
- "인지상태", "이동상태", "식사상태", "배변/배뇨상태", "보호자이름", "보호자연락처",
41
- "특이사항", "비고", "기관유형", "기관명"
42
- ]
43
- REQUIRED_EXCEL_COLUMNS = ["수급자이름", "성별", "장기요양등급", "기관유형", "기관명"]
44
- DATE_COLUMNS = ["인정기간시작일", "인정기간종료일", "입소일"]
45
-
46
- EXCEL_TO_DB = {
47
- "수급자이름": "name",
48
- "성별": "gender",
49
- "생년월일": "birth_date",
50
- "실질생일날짜": "real_birth_date",
51
- "장기요양등급": "care_grade",
52
- "인정번호": "recognition_number",
53
- "인정기간시작일": "recognition_start_date",
54
- "인정기간종료일": "recognition_end_date",
55
- "기관유형": "institution_type",
56
- "기관명": "institution_name",
57
- "입소일": "admission_date",
58
- "이용상태": "status",
59
- "주요질환": "main_condition",
60
- "인지상태": "cognitive_status",
61
- "이동상태": "mobility_status",
62
- "식사상태": "diet_status",
63
- "배변/배뇨상태": "toileting_status",
64
- "보호자이름": "guardian_name",
65
- "보호자연락처": "guardian_phone",
66
- "특이사항": "notes",
67
- "비고": "remarks",
68
- }
69
-
70
- COLUMN_ALIASES = {
71
- "NO.": "NO.",
72
- "수급자이름": "수급자이름",
73
- "성별": "성별",
74
- "생년월일": "생년월일",
75
- "실질생일날짜": "실질생일날짜",
76
- "장기요양등급": "장기요양등급",
77
- "인정번호": "인정번호",
78
- "인정기간시작일": "인정기간시작일",
79
- "인정기간종료일": "인정기간종료일",
80
- "입소일": "입소일",
81
- "이용상태": "이용상태",
82
- "주요질환": "주요질환",
83
- "인지상태": "인지상태",
84
- "이동상태": "이동상태",
85
- "식사상태": "식사상태",
86
- "배변/배뇨상태": "배변/배뇨상태",
87
- "보호자이름": "보호자이름",
88
- "보호자연락처": "보호자연락처",
89
- "특이사항": "특이사항",
90
- "비고": "비고",
91
- "기관유형": "기관유형",
92
- "기관명": "기관명",
93
-
94
- # aliases
95
- "성명": "수급자이름",
96
- "이름": "수급자이름",
97
- "수급자 이름": "수급자이름",
98
- "수급자명": "수급자이름",
99
- "출생연도": "생년월일",
100
- "등급": "장기요양등급",
101
- "장기요양 등급": "장기요양등급",
102
- "인정 번호": "인정번호",
103
- "인정유효기간 시작일": "인정기간시작일",
104
- "인정기간 시작일": "인정기간시작일",
105
- "인정유효기간 종료일": "인정기간종료일",
106
- "인정기간 종료일": "인정기간종료일",
107
- "이용시작일": "입소일",
108
- "이용 시작일": "입소일",
109
- "입소일자": "입소일",
110
- "상태": "이용상태",
111
- "이용 상태": "이용상태",
112
- "질환": "주요질환",
113
- "주요 질환": "주요질환",
114
- "인지 상태": "인지상태",
115
- "이동 상태": "이동상태",
116
- "식사 상태": "식사상태",
117
- "배변/배뇨 상태": "배변/배뇨상태",
118
- "보호자": "보호자이름",
119
- "보호자 이름": "보호자이름",
120
- "보호자 성명": "보호자이름",
121
- "연락처": "보호자연락처",
122
- "메모": "비고",
123
- "기관 유형": "기관유형",
124
- "기관명칭": "기관명"
125
- }
126
-
127
- def normalize_real_birth_date(value):
128
- """실질생일날짜를 MM-DD 형식으로 변환합니다."""
129
- v = safe(value).replace(" ", "").replace("/", "-").replace(".", "-")
130
- if not v:
131
- return ""
132
- # YYYY-MM-DD 인 경우
133
- if re.match(r"^\d{4}-\d{2}-\d{2}$", v):
134
- return v[5:10]
135
- # MM-DD 인 경우
136
- if re.match(r"^\d{2}-\d{2}$", v):
137
- return v
138
- # M-D 인 경우 (자릿수 보정)
139
- parts = v.split("-")
140
- if len(parts) == 2:
141
- try:
142
- m = int(parts[0])
143
- d = int(parts[1])
144
- if 1 <= m <= 12 and 1 <= d <= 31:
145
- return f"{m:02d}-{d:02d}"
146
- except ValueError:
147
- pass
148
- return v
149
-
150
-
151
- def get_conn():
152
- return sqlite3.connect(DB_PATH, check_same_thread=False)
153
-
154
-
155
- def safe(value, default=""):
156
- if value is None:
157
- return default
158
- try:
159
- if pd.isna(value):
160
- return default
161
- except Exception:
162
- pass
163
- return str(value).strip()
164
-
165
-
166
- def mask_name(name):
167
- name = safe(name)
168
- if len(name) >= 3:
169
- return name[0] + "○" + name[2:]
170
- if len(name) == 2:
171
- return name[0] + "○"
172
- return name
173
-
174
-
175
- def normalize_recognition_number(value):
176
- """숫자만 입력해도 L을 붙여 저장합니다. 빈칸은 빈칸으로 둡니다."""
177
- v = safe(value).replace(" ", "")
178
- if not v:
179
- return ""
180
- v = v.replace("l", "L")
181
- if v.startswith("L"):
182
- return "L" + re.sub(r"[^0-9]", "", v[1:])
183
- digits = re.sub(r"[^0-9]", "", v)
184
- return f"L{digits}" if digits else v
185
-
186
-
187
- def normalize_date_text(value):
188
- """날짜를 YYYY-MM-DD 문자열로 정리합니다. 변환 불가 값은 원문을 유지해 검증에서 안내합니다."""
189
- v = safe(value)
190
- if not v:
191
- return ""
192
- try:
193
- dt = pd.to_datetime(v, errors="raise")
194
- return dt.strftime("%Y-%m-%d")
195
- except Exception:
196
- return v
197
-
198
-
199
- def is_valid_date_text(value):
200
- v = safe(value)
201
- if not v:
202
- return True
203
- return bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}", v))
204
-
205
-
206
- def days_until(date_text):
207
- v = normalize_date_text(date_text)
208
- if not is_valid_date_text(v) or not v:
209
- return None
210
- try:
211
- target = datetime.strptime(v, "%Y-%m-%d").date()
212
- return (target - date.today()).days
213
- except Exception:
214
- return None
215
-
216
-
217
- def plan_alert_text(end_date_text):
218
- days = days_until(end_date_text)
219
- if days is None:
220
- return "인정기간 종료일 미입력"
221
- if days < 0:
222
- return f"인정기간 만료 {abs(days)}일 경과"
223
- if days <= 30:
224
- return f"만료 {days}일 전: 급여계획 재검토 필요"
225
- if days <= 90:
226
- return f"만료 {days}일 전: 갱신/계획 확인"
227
- return f"만료 {days}일 전"
228
-
229
-
230
- def get_this_year_birthday(birth_date_str, real_birth_date_str):
231
- now = datetime.now()
232
- this_year = now.year
233
-
234
- md = ""
235
- r_val = safe(real_birth_date_str)
236
- if r_val:
237
- normalized_r = normalize_real_birth_date(r_val)
238
- if re.match(r"^\d{2}-\d{2}$", normalized_r):
239
- md = normalized_r
240
-
241
- if not md:
242
- b_val = normalize_date_text(birth_date_str)
243
- if is_valid_date_text(b_val) and len(b_val) == 10:
244
- md = b_val[5:10]
245
-
246
- if not md:
247
- return None
248
-
249
- try:
250
- m, d = map(int, md.split("-"))
251
- return date(this_year, m, d)
252
- except Exception:
253
- return None
254
-
255
-
256
- def display_birthday_alerts():
257
- df = load_clients()
258
- if df.empty:
259
- return
260
-
261
- today = date.today()
262
- this_month = today.month
263
-
264
- today_birthdays = []
265
- month_birthdays = []
266
-
267
- for _, row in df.iterrows():
268
- b_date = row.get("birth_date")
269
- rb_date = row.get("real_birth_date")
270
- name_masked = mask_name(row.get("name"))
271
-
272
- bday = get_this_year_birthday(b_date, rb_date)
273
- if bday:
274
- if bday.month == today.month and bday.day == today.day:
275
- today_birthdays.append((name_masked, rb_date, b_date))
276
- elif bday.month == this_month:
277
- month_birthdays.append((name_masked, bday.day, rb_date, b_date))
278
-
279
- month_birthdays.sort(key=lambda x: x[1])
280
-
281
- if today_birthdays or month_birthdays:
282
- st.markdown(f"### 🎂 {this_month}월 생신 어르신 알림")
283
-
284
- if today_birthdays:
285
- today_list_str = ", ".join([f"**{name} 어르신**" + (f" (실질생일: {rb})" if rb else f" ({bd[5:10]})" if bd else "") for name, rb, bd in today_birthdays])
286
- st.markdown(f"""
287
- <div style="background: #fff3e0; border-left: 7px solid #fb8c00; padding: 14px; border-radius: 12px; margin-bottom: 14px; color: #222;">
288
- 🎉 <strong>오늘 생신!</strong> 오늘은 {today_list_str}의 생신입니다. 축하드립니다! 🎂
289
- </div>
290
- """, unsafe_allow_html=True)
291
-
292
- if month_birthdays:
293
- items_html = []
294
- for name, day, rb, bd in month_birthdays:
295
- src_info = f"실질생일: {rb}" if rb else f"생년월일: {bd[5:10] if bd else ''}"
296
- items_html.append(f"<li style='margin-bottom: 4px;'><strong>{name} 어르신</strong> ({this_month}월 {day}일 - {src_info})</li>")
297
-
298
- st.markdown(f"""
299
- <div style="background: #e8f5e9; border-left: 7px solid #43a047; padding: 14px; border-radius: 12px; margin-bottom: 14px; color: #222;">
300
- 🎁 <strong>{this_month}월 생신 예정 어르신 목록:</strong>
301
- <ul style="margin: 8px 0 0 20px; padding: 0;">
302
- {"".join(items_html)}
303
- </ul>
304
- </div>
305
- """, unsafe_allow_html=True)
306
-
307
-
308
- def init_db():
309
- conn = get_conn()
310
- cur = conn.cursor()
311
- cur.execute("""
312
- CREATE TABLE IF NOT EXISTS clients (
313
- id INTEGER PRIMARY KEY AUTOINCREMENT,
314
- name TEXT NOT NULL,
315
- masked_name TEXT,
316
- gender TEXT,
317
- birth_year TEXT,
318
- care_grade TEXT,
319
- institution_type TEXT,
320
- institution_name TEXT,
321
- admission_date TEXT,
322
- main_condition TEXT,
323
- cognitive_status TEXT,
324
- mobility_status TEXT,
325
- diet_status TEXT,
326
- toileting_status TEXT,
327
- guardian_name TEXT,
328
- guardian_phone TEXT,
329
- notes TEXT,
330
- status TEXT DEFAULT '이용중',
331
- created_at TEXT,
332
- updated_at TEXT
333
- )
334
- """)
335
-
336
- new_columns = {
337
- "previous_care_grade": "TEXT",
338
- "recognition_number": "TEXT",
339
- "recognition_start_date": "TEXT",
340
- "recognition_end_date": "TEXT",
341
- "plan_change_required": "TEXT DEFAULT '아니오'",
342
- "plan_change_type": "TEXT",
343
- "plan_change_reason": "TEXT",
344
- "plan_change_date": "TEXT",
345
- "plan_rewrite_status": "TEXT DEFAULT '해당없음'",
346
- "service_end_reason": "TEXT",
347
- "service_end_date": "TEXT",
348
- "linked_document": "TEXT",
349
- "birth_date": "TEXT",
350
- "real_birth_date": "TEXT",
351
- "remarks": "TEXT",
352
- }
353
- cur.execute("PRAGMA table_info(clients)")
354
- existing_cols = [row[1] for row in cur.fetchall()]
355
- for col, col_type in new_columns.items():
356
- if col not in existing_cols:
357
- cur.execute(f"ALTER TABLE clients ADD COLUMN {col} {col_type}")
358
-
359
- cur.execute("""
360
- CREATE TABLE IF NOT EXISTS plan_change_logs (
361
- id INTEGER PRIMARY KEY AUTOINCREMENT,
362
- client_id INTEGER,
363
- client_masked_name TEXT,
364
- institution_type TEXT,
365
- change_type TEXT,
366
- change_reason TEXT,
367
- change_date TEXT,
368
- linked_document TEXT,
369
- plan_change_required TEXT,
370
- plan_rewrite_status TEXT,
371
- memo TEXT,
372
- created_at TEXT
373
- )
374
- """)
375
- conn.commit()
376
- conn.close()
377
-
378
-
379
- def load_clients():
380
- conn = get_conn()
381
- df = pd.read_sql_query("SELECT * FROM clients ORDER BY id DESC", conn)
382
- conn.close()
383
- return df
384
-
385
-
386
- def add_no_column(df):
387
- df = df.copy()
388
- if "NO." not in df.columns:
389
- df.insert(0, "NO.", range(1, len(df) + 1))
390
- else:
391
- df["NO."] = range(1, len(df) + 1)
392
- return df
393
-
394
-
395
- def load_change_logs(client_id=None):
396
- conn = get_conn()
397
- if client_id:
398
- df = pd.read_sql_query("SELECT * FROM plan_change_logs WHERE client_id=? ORDER BY id DESC", conn, params=(client_id,))
399
- else:
400
- df = pd.read_sql_query("SELECT * FROM plan_change_logs ORDER BY id DESC", conn)
401
- conn.close()
402
- return df
403
-
404
-
405
- def calculate_plan_change(change_type, change_reason, status):
406
- termination_types = ["사망", "전원", "계약해지", "서비스 종료", "장기입원"]
407
- required_types = ["상태변화", "등급변경", "보호자 요청", "서비스 변경", "사례관리 결과", "욕구사정 결과", "결과평가 반영"]
408
- if change_type in termination_types or status in ["사망", "퇴소", "중지"]:
409
- return "아니오", "종결/중지 처리", "급여제공계획 재작성보다 서비스 종결 또는 중지 기록 정리가 우선입니다."
410
- if change_type in required_types:
411
- return "예", "재작성 필요", "상태변화 또는 서비스 변경 사유가 확인되어 급여제공계획 재작성이 필요합니다."
412
- if any(word in change_reason for word in ["낙상", "욕창", "입원", "퇴원", "식사량", "체중", "등급", "시간", "요일", "서비스", "보호자", "기저귀", "인지", "보행", "피부", "혈압", "혈당"]):
413
- return "예", "재작성 검토", "기록 내용상 급여제공계획 변경 가능성이 있어 재작성 여부를 검토해야 합니다."
414
- return "아니오", "현재계획 유지", "현재 입력 내용만으로는 급여제공계획 재작성 필요성이 높지 않습니다."
415
-
416
-
417
- def institution_change_reasons(inst):
418
- common = ["상���변화", "등급변경", "보호자 요청", "욕구사정 결과", "상담일지 결과", "사례관리 결과", "결과평가 반영", "병원입원", "퇴원 후 재이용", "전원", "사망", "계약해지", "서비스 종료"]
419
- by_inst = {
420
- "방문요양": ["서비스 시간 변경", "서비스 요일 변경", "요양보호사 변경", "인지활동 필요", "가사지원 범위 조정", "복약확인 필요", "낙상위험 증가", "동거가족 상황 변화"],
421
- "방문목욕": ["목욕 거부", "피부상태 변화", "욕창 발생/위험 증가", "목욕 전후 건강상태 변화", "이동방법 변경", "목욕장소 변경", "보호자 협조 필요"],
422
- "방문간호": ["혈압 변화", "혈당 변화", "상처관리 시작", "투약 변경", "간호처치 변경", "의료기관 연계 필요", "건강상담 강화"],
423
- "주간보호": ["송영 변경", "프로그램 참여도 변화", "식사형태 변경", "배변상태 변화", "정서불안 증가", "수급자 간 갈등", "낙상위험 증가"],
424
- "요양원": ["욕창 발생/위험 증가", "낙상 발생/위험 증가", "경관급식 시작", "연하곤란 발생", "기저귀 케어 변경", "수면상태 변화", "프로그램 참여 변화", "인지/행동심리 변화"],
425
- "공동생활가정": ["생활적응 문제", "정서불안 증가", "사회관계 변화", "행동심리증상 변화", "가족소통 변화", "개별욕구 변화", "공동생활 갈등"],
426
- }
427
- return common + by_inst.get(inst, [])
428
-
429
-
430
- def save_change_log(client_id, client_masked_name, institution_type, change_type, change_reason, change_date, linked_document, required, rewrite_status, memo):
431
- conn = get_conn()
432
- cur = conn.cursor()
433
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
434
- cur.execute("""
435
- INSERT INTO plan_change_logs (
436
- client_id, client_masked_name, institution_type, change_type,
437
- change_reason, change_date, linked_document, plan_change_required,
438
- plan_rewrite_status, memo, created_at
439
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
440
- """, (client_id, client_masked_name, institution_type, change_type, change_reason, change_date, linked_document, required, rewrite_status, memo, now))
441
- cur.execute("""
442
- UPDATE clients SET plan_change_required=?, plan_change_type=?, plan_change_reason=?,
443
- plan_change_date=?, plan_rewrite_status=?, linked_document=?, updated_at=? WHERE id=?
444
- """, (required, change_type, change_reason, change_date, rewrite_status, linked_document, now, client_id))
445
- conn.commit()
446
- conn.close()
447
-
448
-
449
- def normalize_excel_columns(df):
450
- df = df.copy()
451
- cleaned = []
452
- for c in df.columns:
453
- name = str(c).replace("\n", " ").strip()
454
- # If pandas suffix is present e.g. "주요질환.1"
455
- if "." in name:
456
- parts = name.split(".")
457
- if parts[-1].isdigit() and parts[0] == "주요질환":
458
- name = parts[0]
459
- name = COLUMN_ALIASES.get(name, name)
460
- cleaned.append(name)
461
- df.columns = cleaned
462
-
463
- # Merge duplicate columns (like 주요질환)
464
- duplicate_cols = [col for col in set(df.columns) if list(df.columns).count(col) > 1]
465
- for col in duplicate_cols:
466
- cols_to_merge = df.loc[:, df.columns == col]
467
- merged_series = cols_to_merge.apply(lambda row: ", ".join([str(val).strip() for val in row if str(val).strip()]), axis=1)
468
- df = df.loc[:, df.columns != col]
469
- df[col] = merged_series
470
-
471
- return df
472
-
473
-
474
- def make_client_excel_template():
475
- from openpyxl import Workbook
476
- wb = Workbook()
477
- ws = wb.active
478
- ws.title = "수급자등록양식"
479
-
480
- headers = [
481
- "NO.", "수급자이름", "성별", "생년월일", "실질생일날짜", "장기요양등급", "인정번호",
482
- "인정기간시작일", "인정기간종료일", "입소일", "이용상태", "주요질환", "주요질환",
483
- "인지상태", "이동상태", "식사상태", "배변/배뇨상태", "보호자이름", "보호자연락처",
484
- "특이사항", "비고", "기관유형", "기관명"
485
- ]
486
- sample_data = [
487
- "1", "홍길동", "여", "1942-09-20", "09-20", "3등급", "1234567890",
488
- "2025-03-03", "2027-03-02", "2025-03-05", "이용중", "치매, 고혈압", "당뇨, 낙상위험",
489
- "단기기억 저하", "워커 사용", "일반식", "화장실 유도 필요", "홍보호", "010-0000-0000",
490
- "오전 프로그램 참여 선호", "특이 소견 없음", "주간보호", "행복주간보호센터"
491
- ]
492
- ws.append(headers)
493
- ws.append(sample_data)
494
-
495
- # Guide sheet
496
- guide_ws = wb.create_sheet(title="작성안내")
497
- guide_ws.append(["항목", "입력 안내"])
498
- guide_items = [
499
- ("NO.", "연번 (숫자 입력)"),
500
- ("수급자이름", "필수. 실제 이름으로 입력하면 화면에는 자동 마스킹됩니다."),
501
- ("성별", "여/남/기타 중 선택"),
502
- ("생년월일", "생년월일 입력 (예: 1942-09-20 또는 1942)"),
503
- ("실질생일날짜", "음력 생일 등 실제 생일 입력 (예: 09-20). 없으면 생년월일의 월/일로 계산됩니다."),
504
- ("장기요양등급", "1등급/2등급/3등급/4등급/5등급/인지지원등급/등급외/미입력 중 선택"),
505
- ("인정번호", "숫자만 입력해도 저장 시 L이 자동으로 붙습니다. 예: 1234567890 → L1234567890"),
506
- ("인정기간시작일", "반드시 YYYY-MM-DD 형식. 예: 2025-03-03"),
507
- ("인정기간종료일", "반드시 YYYY-MM-DD 형식. 예: 2027-03-02"),
508
- ("입소일", "반드시 YYYY-MM-DD 형식. 예: 2025-03-05"),
509
- ("이용상태", "이용중/입소중/퇴소/중지/사망 중 선택"),
510
- ("주요질환", "주요 질환 및 상태 기술"),
511
- ("주요질환 (추가)", "추가 질환이 있을 경우 작성 (두 컬럼의 내용이 자동 병합되어 저장됩니다)"),
512
- ("인지상태", "기억력, 지남력, 의사소통 등"),
513
- ("이동상태", "보행, 휠체어, 부축 여부 등"),
514
- ("식사상태", "일반식, 죽식, 연하곤란, 식사보조 등"),
515
- ("배변/배뇨상태", "기저귀, 화장실 유도, 실금 등"),
516
- ("보호자이름", "보호자 성명"),
517
- ("보호자연락처", "전화번호는 문자로 입력 권장"),
518
- ("특이사항", "추가 특이사항"),
519
- ("비고", "기타 참고사항"),
520
- ("기관유형", "방문요양/방문목욕/방문간호/주간보호/요양원/공동생활가정 중 선택"),
521
- ("기관명", "기관명 입력"),
522
- ]
523
- for item in guide_items:
524
- guide_ws.append(item)
525
-
526
- ws.freeze_panes = "A2"
527
- ws.sheet_view.showGridLines = False
528
-
529
- header_fill = PatternFill("solid", fgColor="D9EAD3")
530
- thin = Side(style="thin", color="999999")
531
- border = Border(left=thin, right=thin, top=thin, bottom=thin)
532
- for cell in ws[1]:
533
- cell.font = Font(name="Malgun Gothic", bold=True)
534
- cell.fill = header_fill
535
- cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
536
- cell.border = border
537
- for row in ws.iter_rows(min_row=2, max_row=200, min_col=1, max_col=len(headers)):
538
- for cell in row:
539
- cell.font = Font(name="Malgun Gothic", size=10)
540
- cell.alignment = Alignment(vertical="center", wrap_text=True)
541
- cell.border = border
542
-
543
- widths = [8, 15, 10, 15, 15, 16, 18, 18, 18, 16, 12, 28, 28, 28, 28, 28, 28, 16, 18, 30, 30, 16, 22]
544
- for i, width in enumerate(widths, start=1):
545
- ws.column_dimensions[ws.cell(1, i).column_letter].width = width
546
-
547
- def add_dropdown_by_idx(col_idx, options):
548
- letter = ws.cell(1, col_idx).column_letter
549
- dv = DataValidation(type="list", formula1='"' + ",".join(options) + '"', allow_blank=True)
550
- ws.add_data_validation(dv)
551
- dv.add(f"{letter}2:{letter}500")
552
-
553
- add_dropdown_by_idx(headers.index("성별") + 1, VALID_GENDERS)
554
- add_dropdown_by_idx(headers.index("장기요양등급") + 1, VALID_GRADES)
555
- add_dropdown_by_idx(headers.index("이용상태") + 1, VALID_STATUS)
556
- add_dropdown_by_idx(headers.index("기관유형") + 1, VALID_INST_TYPES)
557
-
558
- guide_ws.sheet_view.showGridLines = False
559
- guide_ws.column_dimensions["A"].width = 22
560
- guide_ws.column_dimensions["B"].width = 90
561
- for row in guide_ws.iter_rows():
562
- for cell in row:
563
- cell.font = Font(name="Malgun Gothic", size=10, bold=(cell.row == 1))
564
- cell.alignment = Alignment(vertical="center", wrap_text=True)
565
- cell.border = border
566
- if cell.row == 1:
567
- cell.fill = header_fill
568
-
569
- out = BytesIO()
570
- wb.save(out)
571
- out.seek(0)
572
- return out
573
-
574
-
575
-
576
-
577
- def validate_client_excel(df):
578
- errors = []
579
- df = normalize_excel_columns(df)
580
- missing = [c for c in REQUIRED_EXCEL_COLUMNS if c not in df.columns]
581
- if missing:
582
- errors.append("필수 컬럼 누락: " + ", ".join(missing))
583
- allowed_cols = set(EXCEL_COLUMNS)
584
- unknown = [c for c in df.columns if c not in allowed_cols and c != "NO."]
585
- if unknown:
586
- errors.append("양식에 없는 컬럼이 있습니다: " + ", ".join(unknown))
587
- if errors:
588
- return df, errors
589
-
590
- for col in EXCEL_COLUMNS:
591
- if col not in df.columns:
592
- df[col] = ""
593
- df = df[EXCEL_COLUMNS].fillna("")
594
-
595
- for col in DATE_COLUMNS:
596
- df[col] = df[col].apply(normalize_date_text)
597
- df["인정번호"] = df["인정번호"].apply(normalize_recognition_number)
598
- df["실질생일날짜"] = df["실질생일날짜"].apply(normalize_real_birth_date)
599
-
600
- for idx, row in df.iterrows():
601
- row_no = idx + 2
602
- if not safe(row.get("수급자이름")):
603
- errors.append(f"{row_no}행: 수급자이름은 필수입니다.")
604
- if safe(row.get("성별")) and safe(row.get("성별")) not in VALID_GENDERS:
605
- errors.append(f"{row_no}행: 성별은 여/남/기타 중 하나여야 ��니다.")
606
- if safe(row.get("장기요양등급")) and safe(row.get("장기요양등급")) not in VALID_GRADES:
607
- errors.append(f"{row_no}행: 장기요양등급 값이 올바르지 않습니다.")
608
- if safe(row.get("기관유형")) and safe(row.get("기관유형")) not in VALID_INST_TYPES:
609
- errors.append(f"{row_no}행: 기관유형 값이 올바르지 않습니다.")
610
- if safe(row.get("이용상태")) and safe(row.get("이용상태")) not in VALID_STATUS:
611
- errors.append(f"{row_no}행: 이용상태는 이용중/입소중/퇴소/중지/사망 중 하나여야 합니다.")
612
- for col in DATE_COLUMNS:
613
- if safe(row.get(col)) and not is_valid_date_text(row.get(col)):
614
- errors.append(f"{row_no}행: {col}은 2026-03-20 형식으로 입력해야 합니다.")
615
-
616
- bd = safe(row.get("생년월일"))
617
- if bd and not (is_valid_date_text(bd) or (len(bd) == 4 and bd.isdigit())):
618
- errors.append(f"{row_no}행: 생년월일은 1942-09-20 형식 또는 1942 형식으로 입력해야 합니다.")
619
- return df, errors
620
-
621
-
622
- def import_clients_from_excel(df, overwrite=False):
623
- conn = get_conn()
624
- cur = conn.cursor()
625
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
626
- inserted = updated = skipped = 0
627
-
628
- for _, row in df.iterrows():
629
- data = {db_col: safe(row.get(excel_col)) for excel_col, db_col in EXCEL_TO_DB.items()}
630
- if not data.get("name"):
631
- skipped += 1
632
- continue
633
- data["recognition_number"] = normalize_recognition_number(data.get("recognition_number"))
634
- for key in ["recognition_start_date", "recognition_end_date", "admission_date"]:
635
- data[key] = normalize_date_text(data.get(key))
636
- data["gender"] = data.get("gender") if data.get("gender") in VALID_GENDERS else "여"
637
- data["care_grade"] = data.get("care_grade") if data.get("care_grade") in VALID_GRADES else "미입력"
638
- data["institution_type"] = data.get("institution_type") if data.get("institution_type") in VALID_INST_TYPES else "방문요양"
639
- data["status"] = data.get("status") if data.get("status") in VALID_STATUS else "이용중"
640
- data["masked_name"] = mask_name(data.get("name"))
641
-
642
- # Extract birth_year from birth_date
643
- birth_date_val = data.get("birth_date")
644
- birth_year_val = ""
645
- if birth_date_val:
646
- birth_date_val = normalize_date_text(birth_date_val)
647
- data["birth_date"] = birth_date_val
648
- if len(birth_date_val) >= 4 and birth_date_val[:4].isdigit():
649
- birth_year_val = birth_date_val[:4]
650
- data["birth_year"] = birth_year_val
651
-
652
- if data.get("real_birth_date"):
653
- data["real_birth_date"] = normalize_real_birth_date(data.get("real_birth_date"))
654
-
655
- cur.execute("""
656
- SELECT id FROM clients
657
- WHERE name=? AND birth_year=? AND institution_name=?
658
- ORDER BY id DESC LIMIT 1
659
- """, (data.get("name"), data.get("birth_year"), data.get("institution_name")))
660
- existing = cur.fetchone()
661
-
662
- if existing and overwrite:
663
- client_id = existing[0]
664
- cur.execute("""
665
- UPDATE clients SET
666
- masked_name=?, gender=?, birth_year=?, care_grade=?, previous_care_grade=?,
667
- recognition_number=?, recognition_start_date=?, recognition_end_date=?,
668
- institution_type=?, institution_name=?, admission_date=?, main_condition=?,
669
- cognitive_status=?, mobility_status=?, diet_status=?, toileting_status=?,
670
- guardian_name=?, guardian_phone=?, notes=?, status=?, updated_at=?,
671
- birth_date=?, real_birth_date=?, remarks=?
672
- WHERE id=?
673
- """, (
674
- data["masked_name"], data["gender"], data["birth_year"], data["care_grade"], data["care_grade"],
675
- data["recognition_number"], data["recognition_start_date"], data["recognition_end_date"],
676
- data["institution_type"], data["institution_name"], data["admission_date"], data["main_condition"],
677
- data["cognitive_status"], data["mobility_status"], data["diet_status"], data["toileting_status"],
678
- data["guardian_name"], data["guardian_phone"], data["notes"], data["status"], now,
679
- data["birth_date"], data["real_birth_date"], data["remarks"], client_id,
680
- ))
681
- updated += 1
682
- elif existing and not overwrite:
683
- skipped += 1
684
- else:
685
- cur.execute("""
686
- INSERT INTO clients (
687
- name, masked_name, gender, birth_year, care_grade, previous_care_grade,
688
- recognition_number, recognition_start_date, recognition_end_date,
689
- institution_type, institution_name, admission_date,
690
- main_condition, cognitive_status, mobility_status, diet_status, toileting_status,
691
- guardian_name, guardian_phone, notes, status,
692
- plan_change_required, plan_rewrite_status, created_at, updated_at,
693
- birth_date, real_birth_date, remarks
694
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
695
- """, (
696
- data["name"], data["masked_name"], data["gender"], data["birth_year"], data["care_grade"], data["care_grade"],
697
- data["recognition_number"], data["recognition_start_date"], data["recognition_end_date"],
698
- data["institution_type"], data["institution_name"], data["admission_date"],
699
- data["main_condition"], data["cognitive_status"], data["mobility_status"], data["diet_status"], data["toileting_status"],
700
- data["guardian_name"], data["guardian_phone"], data["notes"], data["status"],
701
- "아니오", "해당없음", now, now,
702
- data["birth_date"], data["real_birth_date"], data["remarks"]
703
- ))
704
- inserted += 1
705
- conn.commit()
706
- conn.close()
707
- return inserted, updated, skipped
708
-
709
-
710
- init_db()
711
-
712
- st.markdown("""
713
- <style>
714
- .block-container { padding-top: 2rem; }
715
- .title-box { background: linear-gradient(135deg, #2E7D32, #66BB6A); padding: 28px; border-radius: 18px; color: white; text-align: center; margin-bottom: 25px; }
716
- .title-box h1 { margin: 0; font-size: 34px; }
717
- .title-box p { font-size: 17px; margin-top: 8px; }
718
- .notice { background: #fff8e1; padding: 15px; border-left: 6px solid #f9a825; border-radius: 10px; margin-bottom: 20px; line-height: 1.65; }
719
- .okbox { background: #e8f5e9; border-left: 7px solid #43a047; padding: 14px; border-radius: 12px; margin-bottom: 14px; }
720
- .warnbox { background: #fff3e0; border-left: 7px solid #fb8c00; padding: 14px; border-radius: 12px; margin-bottom: 14px; }
721
- .dangerbox { background: #ffebee; border-left: 7px solid #e53935; padding: 14px; border-radius: 12px; margin-bottom: 14px; }
722
- </style>
723
- """, unsafe_allow_html=True)
724
-
725
- st.markdown("""
726
- <div class="title-box">
727
- <h1>👥 Client Center</h1>
728
- <p>수급자 등록 / 엑셀 업로드 / 검색 / 수정 / 급여제공계획 재작성 필요 여부 중앙관리</p>
729
- </div>
730
- """, unsafe_allow_html=True)
731
-
732
- display_birthday_alerts()
733
-
734
- st.markdown("""
735
- <div class="notice">
736
- <strong>날짜 입력 안내:</strong> 날짜는 반드시 <strong>2026-03-20</strong> 형식으로 입력해 주세요.<br>
737
- 인정기간은 한 칸에 쓰지 말고 <strong>인정기간 시작일</strong>과 <strong>인정기간 종료일</strong>을 각각 입력해 주세요.<br>
738
- 인정번호는 숫자만 입력해도 저장 시 <strong>L</strong>이 자동으로 붙습니다. 예: 1234567890 → L1234567890
739
- </div>
740
- """, unsafe_allow_html=True)
741
-
742
- menu = st.sidebar.radio("메뉴 선택", ["수급자 등록", "엑셀 업로드", "수급자 목록", "수급자 검색", "수정 / 삭제", "급여계획 변경관리", "변경이력 보기"])
743
-
744
- # -----------------------------
745
- # 수급자 등록
746
- # -----------------------------
747
- if menu == "수급자 등록":
748
- st.subheader("📝 수급자 직접 등록")
749
- with st.form("client_form"):
750
- col1, col2, col3 = st.columns(3)
751
- with col1:
752
- name = st.text_input("수급자 이름")
753
- gender = st.selectbox("성별", VALID_GENDERS)
754
- birth_date_raw = st.text_input("생년월일", placeholder="예: 1942-09-20 또는 1942")
755
- with col2:
756
- care_grade = st.selectbox("장기요양등급", VALID_GRADES)
757
- recognition_number_raw = st.text_input("인정번호", placeholder="숫자만 입력해도 L 자동 생성")
758
- institution_type = st.selectbox("기관 유형", VALID_INST_TYPES)
759
- with col3:
760
- institution_name = st.text_input("기관명")
761
- admission_date = st.text_input("이용 시작일 / 입소일", placeholder="예: 2026-03-20")
762
- status = st.selectbox("상태", VALID_STATUS)
763
-
764
- col4, col5 = st.columns(2)
765
- with col4:
766
- recognition_start_date = st.text_input("인정기간 시작일", placeholder="예: 2025-03-03")
767
- with col5:
768
- recognition_end_date = st.text_input("인정기간 종료일", placeholder="예: 2027-03-02")
769
-
770
- st.markdown("### 건강 및 생활 상태")
771
- c1, c2 = st.columns(2)
772
- with c1:
773
- main_condition = st.text_area("주요 질환 / 상태", placeholder="예: 치매, 고혈압, 당뇨, 낙상위험 등")
774
- cognitive_status = st.text_area("인지 상태", placeholder="예: 단기기억 저하, 지남력 저하 등")
775
- mobility_status = st.text_area("이동 상태", placeholder="예: 워커 사용, 부축 필요, 휠체어 사용 등")
776
- with c2:
777
- diet_status = st.text_area("식사 상태", placeholder="예: 일반식, 죽식, 연하곤란, 식사보조 필요 등")
778
- toileting_status = st.text_area("배변 / 배뇨 상태", placeholder="예: 기저귀 착용, 화장실 유도 필요 등")
779
- notes = st.text_area("특이사항 / 메모")
780
-
781
- st.markdown("### 생일 및 기타 정보")
782
- c_b1, c_b2 = st.columns(2)
783
- with c_b1:
784
- real_birth_date_raw = st.text_input("실질생일날짜 (옵션)", placeholder="예: 09-20 (생신잔치 알림용)")
785
- with c_b2:
786
- remarks = st.text_area("비고")
787
-
788
- st.markdown("### 보호자 정보")
789
- c3, c4 = st.columns(2)
790
- guardian_name = c3.text_input("보호자 이름")
791
- guardian_phone = c4.text_input("보호자 연락처")
792
- submitted = st.form_submit_button("등록하기")
793
-
794
- if submitted:
795
- errors = []
796
- if not name:
797
- errors.append("수급자 이름은 필수입니다.")
798
-
799
- birth_date = normalize_date_text(birth_date_raw)
800
- if birth_date_raw and not (is_valid_date_text(birth_date) or (len(birth_date_raw) == 4 and birth_date_raw.isdigit())):
801
- errors.append("생년월일은 1942-09-20 형식 또는 1942 형식으로 입력해야 합니다.")
802
-
803
- for label, val in [("인정기간 시작일", recognition_start_date), ("인정기간 종료일", recognition_end_date), ("이용 시작일", admission_date)]:
804
- val2 = normalize_date_text(val)
805
- if val2 and not is_valid_date_text(val2):
806
- errors.append(f"{label}은 2026-03-20 형식으로 입력해 주세요.")
807
- if errors:
808
- for err in errors:
809
- st.error(err)
810
- else:
811
- conn = get_conn()
812
- cur = conn.cursor()
813
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
814
- recognition_number = normalize_recognition_number(recognition_number_raw)
815
-
816
- # Extract birth_year
817
- birth_year = ""
818
- if birth_date and len(birth_date) >= 4 and birth_date[:4].isdigit():
819
- birth_year = birth_date[:4]
820
- elif len(birth_date_raw) == 4 and birth_date_raw.isdigit():
821
- birth_year = birth_date_raw
822
-
823
- real_birth_date = normalize_real_birth_date(real_birth_date_raw)
824
-
825
- cur.execute("""
826
- INSERT INTO clients (
827
- name, masked_name, gender, birth_year, care_grade, previous_care_grade,
828
- recognition_number, recognition_start_date, recognition_end_date,
829
- institution_type, institution_name, admission_date,
830
- main_condition, cognitive_status, mobility_status, diet_status, toileting_status,
831
- guardian_name, guardian_phone, notes, status,
832
- plan_change_required, plan_rewrite_status, created_at, updated_at,
833
- birth_date, real_birth_date, remarks
834
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
835
- """, (
836
- name, mask_name(name), gender, birth_year, care_grade, care_grade,
837
- recognition_number, normalize_date_text(recognition_start_date), normalize_date_text(recognition_end_date),
838
- institution_type, institution_name, normalize_date_text(admission_date),
839
- main_condition, cognitive_status, mobility_status, diet_status, toileting_status,
840
- guardian_name, guardian_phone, notes, status,
841
- "아니오", "해당없음", now, now,
842
- birth_date, real_birth_date, remarks
843
- ))
844
- conn.commit()
845
- conn.close()
846
- st.success(f"{mask_name(name)} 수급자가 등록되었습니다. 인정번호: {recognition_number or '미입력'}")
847
-
848
- # -----------------------------
849
- # 엑셀 업로드
850
- # -----------------------------
851
- elif menu == "엑셀 업로드":
852
- st.subheader("📥 수급자 엑셀/CSV 업로드")
853
- st.markdown("""
854
- <div class="notice">
855
- <strong>📌 엑셀/CSV 업로드 안내:</strong><br>
856
- 1. 기본은 <strong>BeeCare 전용 엑셀 양식(.xlsx)</strong>을 사용해 주세요. 엑셀파일을 다운받아 수급자정보를 입력후 업로드해주세요.<br>
857
- 2. 기관에서 사용하던 엑셀 파일도 업로드할 수 있습니다.<br>
858
- 3. 업로드가 안 될 경우: 엑셀에서 <strong>[파일] → [다른 이름으로 저장] → [CSV UTF-8] 또는 [쉼표로 구분된 파일]</strong>로 저장한 뒤 업로드해 주세요.<br>
859
- 4. 그래도 어려우면 <strong>[수급자 직접 등록]</strong>에서 한 분씩 직접 입력하시면 됩니다.<br><br>
860
- <strong>💡 추가 안내사항:</strong><br>
861
- - <strong>실질생일날짜</strong>가 있으면 → 그 날짜로 생신잔치 알림이 생성됩니다.<br>
862
- - <strong>실질생일날짜</strong>가 없으면 → 생년월일의 월/일로 자동 계산됩니다.<br>
863
- - 실질생일날��는 <strong>09-20</strong> 형식으로 입력해도 자동으로 올해 날짜로 변환되어 적용됩니다.<br>
864
- - 기관명과 기관유형은 맨 끝 열에 입력합니다.
865
- </div>
866
- """, unsafe_allow_html=True)
867
- st.download_button("📄 BeeCare 수급자 등록 엑셀 양식 다운로드", data=make_client_excel_template(), file_name="BeeCare_수급자등록양식.xlsx", mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", use_container_width=True)
868
- uploaded_file = st.file_uploader("작성한 파일 업로드 (XLSX 또는 CSV)", type=["xlsx", "csv"], help="BeeCare 양식의 첫 번째 시트이거나 CSV 형식의 파일을 올려주세요.")
869
- overwrite = st.checkbox("같은 수급자명 + 출생연도(생년월일의 연도) + 기관명이 이미 있으면 기존 정보를 업데이트", value=False)
870
- if uploaded_file is not None:
871
- try:
872
- if uploaded_file.name.endswith(".csv"):
873
- try:
874
- df_raw = pd.read_csv(uploaded_file, dtype=str).dropna(how="all").fillna("")
875
- except UnicodeDecodeError:
876
- try:
877
- uploaded_file.seek(0)
878
- df_raw = pd.read_csv(uploaded_file, dtype=str, encoding="cp949").dropna(how="all").fillna("")
879
- except Exception:
880
- uploaded_file.seek(0)
881
- df_raw = pd.read_csv(uploaded_file, dtype=str, encoding="euc-kr").dropna(how="all").fillna("")
882
- else:
883
- df_raw = pd.read_excel(uploaded_file, dtype=str, sheet_name=0).dropna(how="all").fillna("")
884
-
885
- df_raw = normalize_excel_columns(df_raw)
886
- st.markdown("### 업로드 미리보기")
887
- st.dataframe(df_raw.head(30), use_container_width=True)
888
- df_valid, errors = validate_client_excel(df_raw)
889
- if errors:
890
- st.error("양식 또는 입력값에 문제가 있습니다.")
891
- for err in errors[:50]:
892
- st.write("- " + err)
893
- if len(errors) > 50:
894
- st.write(f"...외 {len(errors) - 50}건")
895
- else:
896
- st.success("검증 완료. 인정번호 L 자동 변환 및 날짜 형식 확인이 완료되었습니다.")
897
- st.dataframe(df_valid.head(30), use_container_width=True)
898
- if st.button("✅ 데이터 DB에 저장하기", use_container_width=True):
899
- inserted, updated, skipped = import_clients_from_excel(df_valid, overwrite=overwrite)
900
- st.success(f"저장 완료: 신규 {inserted}명 / 업데이트 {updated}명 / 건너뜀 {skipped}명")
901
- except Exception as e:
902
- st.error(f"파일을 읽는 중 오류가 발생했습니다: {e}")
903
-
904
- # -----------------------------
905
- # 목록
906
- # -----------------------------
907
- elif menu == "수급자 목록":
908
- st.subheader("📋 수급자 목록")
909
- df = load_clients()
910
- if df.empty:
911
- st.info("등록된 수급자가 없습니다.")
912
- else:
913
- df = add_no_column(df)
914
- df["급여계획 알림"] = df["recognition_end_date"].apply(plan_alert_text) if "recognition_end_date" in df.columns else ""
915
- show_cols = ["NO.", "id", "masked_name", "gender", "birth_date", "real_birth_date", "care_grade", "recognition_number", "recognition_start_date", "recognition_end_date", "급여계획 알림", "institution_type", "institution_name", "status", "plan_change_required", "plan_change_type", "plan_rewrite_status", "admission_date", "remarks"]
916
- existing = [c for c in show_cols if c in df.columns]
917
- st.dataframe(df[existing], use_container_width=True)
918
- buffer = BytesIO()
919
- with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
920
- df[existing].to_excel(writer, index=False, sheet_name="수급자목록")
921
- buffer.seek(0)
922
- st.download_button("📥 수급자 목록 엑셀 다운로드", data=buffer, file_name=f"수급자목록_{datetime.now().strftime('%Y%m%d')}.xlsx", mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", use_container_width=True)
923
-
924
- # -----------------------------
925
- # 검색
926
- # -----------------------------
927
- elif menu == "수급자 검색":
928
- st.subheader("🔍 수급자 검색")
929
- st.caption("수급자 이름 또는 NO. 번호로 검색할 수 있습니다.")
930
- df = add_no_column(load_clients())
931
- keyword = st.text_input("수급자 이름으로 검색")
932
- search_no = st.text_input("NO.로 검색")
933
- if keyword or search_no:
934
- result = df.copy()
935
- if keyword:
936
- keyword = keyword.strip()
937
- result = result[result["name"].astype(str).str.contains(keyword, case=False, na=False) | result["masked_name"].astype(str).str.contains(keyword, case=False, na=False)]
938
- if search_no:
939
- result = result[result["NO."].astype(str) == search_no.strip()]
940
- if result.empty:
941
- st.warning("검색 결과가 없습니다.")
942
- else:
943
- st.dataframe(result, use_container_width=True)
944
-
945
- # -----------------------------
946
- # 수정 / 삭제
947
- # -----------------------------
948
- elif menu == "수정 / 삭제":
949
- st.subheader("✏️ 수급자 정보 수정 / 삭제")
950
- df = load_clients()
951
- if df.empty:
952
- st.info("수정할 수급자가 없습니다.")
953
- else:
954
- options = df.apply(lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_name']}", axis=1).tolist()
955
- selected = st.selectbox("수정할 수급자 선택", options)
956
- selected_id = int(selected.split("번")[0])
957
- c = df[df["id"] == selected_id].iloc[0]
958
- with st.form("edit_form"):
959
- col1, col2, col3 = st.columns(3)
960
- with col1:
961
- name = st.text_input("수급자 이름", value=safe(c.get("name")))
962
- gender = st.selectbox("성별", VALID_GENDERS, index=VALID_GENDERS.index(safe(c.get("gender"))) if safe(c.get("gender")) in VALID_GENDERS else 0)
963
- birth_date_raw = st.text_input("생년월일", value=safe(c.get("birth_date")), placeholder="예: 1942-09-20 또는 1942")
964
- with col2:
965
- old_grade = safe(c.get("care_grade"))
966
- care_grade = st.selectbox("장기요양등급", VALID_GRADES, index=VALID_GRADES.index(old_grade) if old_grade in VALID_GRADES else 7)
967
- recognition_number = st.text_input("인정번호", value=safe(c.get("recognition_number")), help="숫자만 입력해도 L이 자동으로 붙습니다.")
968
- institution_type = st.selectbox("기관 유형", VALID_INST_TYPES, index=VALID_INST_TYPES.index(safe(c.get("institution_type"))) if safe(c.get("institution_type")) in VALID_INST_TYPES else 0)
969
- with col3:
970
- institution_name = st.text_input("기관명", value=safe(c.get("institution_name")))
971
- admission_date = st.text_input("이용 시작일 / 입소일", value=safe(c.get("admission_date")), placeholder="예: 2026-03-20")
972
- status = st.selectbox("상태", VALID_STATUS, index=VALID_STATUS.index(safe(c.get("status"))) if safe(c.get("status")) in VALID_STATUS else 0)
973
-
974
- col4, col5 = st.columns(2)
975
- recognition_start_date = col4.text_input("인정기간 시작일", value=safe(c.get("recognition_start_date")), placeholder="예: 2025-03-03")
976
- recognition_end_date = col5.text_input("인정기간 종료일", value=safe(c.get("recognition_end_date")), placeholder="예: 2027-03-02")
977
-
978
- main_condition = st.text_area("주요 질환 / 상태", value=safe(c.get("main_condition")))
979
- cognitive_status = st.text_area("인지 상태", value=safe(c.get("cognitive_status")))
980
- mobility_status = st.text_area("이동 상태", value=safe(c.get("mobility_status")))
981
- diet_status = st.text_area("식사 상태", value=safe(c.get("diet_status")))
982
- toileting_status = st.text_area("배변 / 배뇨 상태", value=safe(c.get("toileting_status")))
983
- guardian_name = st.text_input("보호자 이름", value=safe(c.get("guardian_name")))
984
- guardian_phone = st.text_input("보호자 연락처", value=safe(c.get("guardian_phone")))
985
- notes = st.text_area("특이사항 / 메모", value=safe(c.get("notes")))
986
-
987
- st.markdown("### 생일 및 기타 정보")
988
- c_b1, c_b2 = st.columns(2)
989
- real_birth_date_raw = c_b1.text_input("실질생일날짜 (옵션)", value=safe(c.get("real_birth_date")), placeholder="예: 09-20 (생신잔치 알림용)")
990
- remarks = c_b2.text_area("비고", value=safe(c.get("remarks")))
991
-
992
- save_btn = st.form_submit_button("수정 저장")
993
- if save_btn:
994
- errors = []
995
- birth_date = normalize_date_text(birth_date_raw)
996
- if birth_date_raw and not (is_valid_date_text(birth_date) or (len(birth_date_raw) == 4 and birth_date_raw.isdigit())):
997
- errors.append("생년월일은 1942-09-20 형식 또는 1942 형식으로 입력해야 합니다.")
998
- for label, val in [("인정기간 시작일", recognition_start_date), ("인정기간 종료일", recognition_end_date), ("이용 시작일", admission_date)]:
999
- val2 = normalize_date_text(val)
1000
- if val2 and not is_valid_date_text(val2):
1001
- errors.append(f"{label}은 2026-03-20 형식으로 입력해 주세요.")
1002
- if errors:
1003
- for err in errors:
1004
- st.error(err)
1005
- else:
1006
- conn = get_conn()
1007
- cur = conn.cursor()
1008
- now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1009
- detected_required = safe(c.get("plan_change_required"), "아니오")
1010
- detected_type = safe(c.get("plan_change_type"))
1011
- detected_reason = safe(c.get("plan_change_reason"))
1012
- detected_date = safe(c.get("plan_change_date"))
1013
- detected_status = safe(c.get("plan_rewrite_status"), "해당없음")
1014
- if old_grade and care_grade != old_grade:
1015
- detected_required, detected_status, auto_memo = calculate_plan_change("등급변경", f"{old_grade}에서 {care_grade}로 변경", status)
1016
- detected_type = "등급변경"
1017
- detected_reason = f"장기요양등급 변경: {old_grade} → {care_grade}"
1018
- detected_date = str(date.today())
1019
- save_change_log(selected_id, safe(c.get("masked_name")), institution_type, detected_type, detected_reason, detected_date, "Client Center 정보수정", detected_required, detected_status, auto_memo)
1020
-
1021
- # Extract birth_year
1022
- birth_year = ""
1023
- if birth_date and len(birth_date) >= 4 and birth_date[:4].isdigit():
1024
- birth_year = birth_date[:4]
1025
- elif len(birth_date_raw) == 4 and birth_date_raw.isdigit():
1026
- birth_year = birth_date_raw
1027
-
1028
- real_birth_date = normalize_real_birth_date(real_birth_date_raw)
1029
-
1030
- cur.execute("""
1031
- UPDATE clients SET name=?, masked_name=?, gender=?, birth_year=?, care_grade=?, previous_care_grade=?,
1032
- recognition_number=?, recognition_start_date=?, recognition_end_date=?,
1033
- institution_type=?, institution_name=?, admission_date=?, main_condition=?, cognitive_status=?, mobility_status=?,
1034
- diet_status=?, toileting_status=?, guardian_name=?, guardian_phone=?, notes=?, status=?,
1035
- plan_change_required=?, plan_change_type=?, plan_change_reason=?, plan_change_date=?, plan_rewrite_status=?, updated_at=?,
1036
- birth_date=?, real_birth_date=?, remarks=?
1037
- WHERE id=?
1038
- """, (
1039
- name, mask_name(name), gender, birth_year, care_grade, old_grade,
1040
- normalize_recognition_number(recognition_number), normalize_date_text(recognition_start_date), normalize_date_text(recognition_end_date),
1041
- institution_type, institution_name, normalize_date_text(admission_date), main_condition, cognitive_status, mobility_status,
1042
- diet_status, toileting_status, guardian_name, guardian_phone, notes, status,
1043
- detected_required, detected_type, detected_reason, detected_date, detected_status, now,
1044
- birth_date, real_birth_date, remarks, selected_id,
1045
- ))
1046
- conn.commit()
1047
- conn.close()
1048
- st.success("수급자 정보가 수정되었습니다.")
1049
- st.divider()
1050
- if st.button("⚠️ 이 수급자 삭제하기"):
1051
- conn = get_conn()
1052
- cur = conn.cursor()
1053
- cur.execute("DELETE FROM clients WHERE id = ?", (selected_id,))
1054
- conn.commit()
1055
- conn.close()
1056
- st.warning("수급자 정보가 삭제되었습니다.")
1057
-
1058
- # -----------------------------
1059
- # 급여계획 변경관리
1060
- # -----------------------------
1061
- elif menu == "급여계획 변경관리":
1062
- st.subheader("🔁 급여제공계획 재작성 필요 여부 관리")
1063
- df = load_clients()
1064
- if df.empty:
1065
- st.info("등록된 수급자가 없습니다.")
1066
- else:
1067
- options = df.apply(lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_type']} / {x['status']}", axis=1).tolist()
1068
- selected = st.selectbox("수급자 선택", options)
1069
- selected_id = int(selected.split("번")[0])
1070
- c = df[df["id"] == selected_id].iloc[0]
1071
- st.markdown("### 현재 상태")
1072
- m1, m2, m3, m4, m5 = st.columns(5)
1073
- m1.metric("수급자", safe(c.get("masked_name")))
1074
- m2.metric("등급", safe(c.get("care_grade")))
1075
- m3.metric("기관유형", safe(c.get("institution_type")))
1076
- m4.metric("재작성 필요", safe(c.get("plan_change_required"), "아니오"))
1077
- m5.metric("인정기간 알림", plan_alert_text(safe(c.get("recognition_end_date"))))
1078
- current_required = safe(c.get("plan_change_required"), "아니오")
1079
- if current_required == "예":
1080
- st.markdown(f'<div class="dangerbox"><strong>급여제공계획 재작성 필요:</strong> {safe(c.get("plan_change_reason"))}</div>', unsafe_allow_html=True)
1081
- else:
1082
- st.markdown(f'<div class="okbox"><strong>현재 상태:</strong> {safe(c.get("plan_rewrite_status"), "해당없음")}</div>', unsafe_allow_html=True)
1083
-
1084
- st.markdown("### 변경사유 입력")
1085
- inst = safe(c.get("institution_type"), "방문요양")
1086
- reason_options = institution_change_reasons(inst)
1087
- col1, col2, col3 = st.columns(3)
1088
- change_type = col1.selectbox("변경유형", ["상태변화", "등급변경", "보호자 요청", "서비스 변경", "욕구사정 결과", "상담일지 결과", "사례관리 결과", "결과평가 반영", "병원입원", "퇴원 후 재이용", "전원", "사망", "계약해지", "서비스 종료", "기타"])
1089
- change_reason_preset = col2.selectbox("기관유형별 변경사유", reason_options)
1090
- change_date = col3.date_input("발생일 / 확인일", value=date.today())
1091
- linked_document = st.multiselect("연동 근거 문서", ["상담일지", "욕구사정", "사례관리", "급여제공 결과평가", "상태변화기록지", "보호자 상담", "공단 인정서", "병원진료/입퇴원 서류", "기타"], default=["상담일지"])
1092
- detail_reason = st.text_area("세부 변경사유", value=f"{change_reason_preset} 관련 상태변화 또는 서비스 조정 필요성 확인", height=100)
1093
- required, rewrite_status, memo = calculate_plan_change(change_type, detail_reason, safe(c.get("status")))
1094
- r1, r2, r3 = st.columns(3)
1095
- r1.metric("재작성 필요 여부", required)
1096
- r2.metric("처리상태", rewrite_status)
1097
- r3.metric("근거문서", ", ".join(linked_document))
1098
- st.warning(memo) if required == "예" else st.info(memo)
1099
- if st.button("💾 변경사유 저장 및 수급자 상태 반영", use_container_width=True):
1100
- save_change_log(selected_id, safe(c.get("masked_name")), inst, change_type, detail_reason, str(change_date), ", ".join(linked_document), required, rewrite_status, memo)
1101
- st.success("변경사유가 저장되었고 Client Center에 반영되었습니다.")
1102
- st.markdown("### 이 수급자의 변경이력")
1103
- logs = load_change_logs(selected_id)
1104
- st.dataframe(logs, use_container_width=True) if not logs.empty else st.info("저장된 변경이력이 없습니다.")
1105
-
1106
- # -----------------------------
1107
- # 변경이력 보기
1108
- # -----------------------------
1109
- elif menu == "변경이력 보기":
1110
- st.subheader("📚 전체 급여제공계획 변경이력")
1111
- logs = load_change_logs()
1112
- st.dataframe(logs, use_container_width=True) if not logs.empty else st.info("저장된 변경이력이 없습니다.")