devorah-ai-2016 commited on
Commit
978b794
·
verified ·
1 Parent(s): 93c9886

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +1103 -0
app.py ADDED
@@ -0,0 +1,1103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 load_change_logs(client_id=None):
387
+ conn = get_conn()
388
+ if client_id:
389
+ df = pd.read_sql_query("SELECT * FROM plan_change_logs WHERE client_id=? ORDER BY id DESC", conn, params=(client_id,))
390
+ else:
391
+ df = pd.read_sql_query("SELECT * FROM plan_change_logs ORDER BY id DESC", conn)
392
+ conn.close()
393
+ return df
394
+
395
+
396
+ def calculate_plan_change(change_type, change_reason, status):
397
+ termination_types = ["사망", "전원", "계약해지", "서비스 종료", "장기입원"]
398
+ required_types = ["상태변화", "등급변경", "보호자 요청", "서비스 변경", "사례관리 결과", "욕구사정 결과", "결과평가 반영"]
399
+ if change_type in termination_types or status in ["사망", "퇴소", "중지"]:
400
+ return "아니오", "종결/중지 처리", "급여제공계획 재작성보다 서비스 종결 또는 중지 기록 정리가 우선입니다."
401
+ if change_type in required_types:
402
+ return "예", "재작성 필요", "상태변화 또는 서비스 변경 사유가 확인되어 급여제공계획 재작성이 필요합니다."
403
+ if any(word in change_reason for word in ["낙상", "욕창", "입원", "퇴원", "식사량", "체중", "등급", "시간", "요일", "서비스", "보호자", "기저귀", "인지", "보행", "피부", "혈압", "혈당"]):
404
+ return "예", "재작성 검토", "기록 내용상 급여제공계획 변경 가능성이 있어 재작성 여부를 검토해야 합니다."
405
+ return "아니오", "현재계획 유지", "현재 입력 내용만으로는 급여제공계획 재작성 필요성이 높지 않습니다."
406
+
407
+
408
+ def institution_change_reasons(inst):
409
+ common = ["상태변화", "등급변경", "보호자 요청", "욕구사정 결과", "상담일지 결과", "사례관리 결과", "결과평가 반영", "병원입원", "퇴원 후 재이용", "전원", "사망", "��약해지", "서비스 종료"]
410
+ by_inst = {
411
+ "방문요양": ["서비스 시간 변경", "서비스 요일 변경", "요양보호사 변경", "인지활동 필요", "가사지원 범위 조정", "복약확인 필요", "낙상위험 증가", "동거가족 상황 변화"],
412
+ "방문목욕": ["목욕 거부", "피부상태 변화", "욕창 발생/위험 증가", "목욕 전후 건강상태 변화", "이동방법 변경", "목욕장소 변경", "보호자 협조 필요"],
413
+ "방문간호": ["혈압 변화", "혈당 변화", "상처관리 시작", "투약 변경", "간호처치 변경", "의료기관 연계 필요", "건강상담 강화"],
414
+ "주간보호": ["송영 변경", "프로그램 참여도 변화", "식사형태 변경", "배변상태 변화", "정서불안 증가", "수급자 간 갈등", "낙상위험 증가"],
415
+ "요양원": ["욕창 발생/위험 증가", "낙상 발생/위험 증가", "경관급식 시작", "연하곤란 발생", "기저귀 케어 변경", "수면상태 변화", "프로그램 참여 변화", "인지/행동심리 변화"],
416
+ "공동생활가정": ["생활적응 문제", "정서불안 증가", "사회관계 변화", "행동심리증상 변화", "가족소통 변화", "개별욕구 변화", "공동생활 갈등"],
417
+ }
418
+ return common + by_inst.get(inst, [])
419
+
420
+
421
+ def save_change_log(client_id, client_masked_name, institution_type, change_type, change_reason, change_date, linked_document, required, rewrite_status, memo):
422
+ conn = get_conn()
423
+ cur = conn.cursor()
424
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
425
+ cur.execute("""
426
+ INSERT INTO plan_change_logs (
427
+ client_id, client_masked_name, institution_type, change_type,
428
+ change_reason, change_date, linked_document, plan_change_required,
429
+ plan_rewrite_status, memo, created_at
430
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
431
+ """, (client_id, client_masked_name, institution_type, change_type, change_reason, change_date, linked_document, required, rewrite_status, memo, now))
432
+ cur.execute("""
433
+ UPDATE clients SET plan_change_required=?, plan_change_type=?, plan_change_reason=?,
434
+ plan_change_date=?, plan_rewrite_status=?, linked_document=?, updated_at=? WHERE id=?
435
+ """, (required, change_type, change_reason, change_date, rewrite_status, linked_document, now, client_id))
436
+ conn.commit()
437
+ conn.close()
438
+
439
+
440
+ def normalize_excel_columns(df):
441
+ df = df.copy()
442
+ cleaned = []
443
+ for c in df.columns:
444
+ name = str(c).replace("\n", " ").strip()
445
+ # If pandas suffix is present e.g. "주요질환.1"
446
+ if "." in name:
447
+ parts = name.split(".")
448
+ if parts[-1].isdigit() and parts[0] == "주요질환":
449
+ name = parts[0]
450
+ name = COLUMN_ALIASES.get(name, name)
451
+ cleaned.append(name)
452
+ df.columns = cleaned
453
+
454
+ # Merge duplicate columns (like 주요질환)
455
+ duplicate_cols = [col for col in set(df.columns) if list(df.columns).count(col) > 1]
456
+ for col in duplicate_cols:
457
+ cols_to_merge = df.loc[:, df.columns == col]
458
+ merged_series = cols_to_merge.apply(lambda row: ", ".join([str(val).strip() for val in row if str(val).strip()]), axis=1)
459
+ df = df.loc[:, df.columns != col]
460
+ df[col] = merged_series
461
+
462
+ return df
463
+
464
+
465
+ def make_client_excel_template():
466
+ from openpyxl import Workbook
467
+ wb = Workbook()
468
+ ws = wb.active
469
+ ws.title = "수급자등록양식"
470
+
471
+ headers = [
472
+ "NO.", "수급자이름", "성별", "생년월일", "실질생일날짜", "장기요양등급", "인정번호",
473
+ "인정기간시작일", "인정기간종료일", "입소일", "이용상태", "주요질환", "주요질환",
474
+ "인지상태", "이동상태", "식사상태", "배변/배뇨상태", "보호자이름", "보호자연락처",
475
+ "특이사항", "비고", "기관유형", "기관명"
476
+ ]
477
+ sample_data = [
478
+ "1", "홍길동", "여", "1942-09-20", "09-20", "3등급", "1234567890",
479
+ "2025-03-03", "2027-03-02", "2025-03-05", "이용중", "치매, 고혈압", "당뇨, 낙상위험",
480
+ "단기기억 저하", "워커 사용", "일반식", "화장실 유도 필요", "홍보호", "010-0000-0000",
481
+ "오전 프로그램 참여 선호", "특이 소견 없음", "주간보호", "행복주간보호센터"
482
+ ]
483
+ ws.append(headers)
484
+ ws.append(sample_data)
485
+
486
+ # Guide sheet
487
+ guide_ws = wb.create_sheet(title="작성안내")
488
+ guide_ws.append(["항목", "입력 안내"])
489
+ guide_items = [
490
+ ("NO.", "연번 (숫자 입력)"),
491
+ ("수급자이름", "필수. 실제 이름으로 입력하면 화면에는 자동 마스킹됩니다."),
492
+ ("성별", "여/남/기타 중 선택"),
493
+ ("생년월일", "생년월일 입력 (예: 1942-09-20 또는 1942)"),
494
+ ("실질생일날짜", "음력 생일 등 실제 생일 입력 (예: 09-20). 없으면 생년월일의 월/일로 계산됩니다."),
495
+ ("장기��양등급", "1등급/2등급/3등급/4등급/5등급/인지지원등급/등급외/미입력 중 선택"),
496
+ ("인정번호", "숫자만 입력해도 저장 시 L이 자동으로 붙습니다. 예: 1234567890 → L1234567890"),
497
+ ("인정기간시작일", "반드시 YYYY-MM-DD 형식. 예: 2025-03-03"),
498
+ ("인정기간종료일", "반드시 YYYY-MM-DD 형식. 예: 2027-03-02"),
499
+ ("입소일", "반드시 YYYY-MM-DD 형식. 예: 2025-03-05"),
500
+ ("이용상태", "이용중/입소중/퇴소/중지/사망 중 선택"),
501
+ ("주요질환", "주요 질환 및 상태 기술"),
502
+ ("주요질환 (추가)", "추가 질환이 있을 경우 작성 (두 컬럼의 내용이 자동 병합되어 저장됩니다)"),
503
+ ("인지상태", "기억력, 지남력, 의사소통 등"),
504
+ ("이동상태", "보행, 휠체어, 부축 여부 등"),
505
+ ("식사상태", "일반식, 죽식, 연하곤란, 식사보조 등"),
506
+ ("배변/배뇨상태", "기저귀, 화장실 유도, 실금 등"),
507
+ ("보호자이름", "보호자 성명"),
508
+ ("보호자연락처", "전화번호는 문자로 입력 권장"),
509
+ ("특이사항", "추가 특이사항"),
510
+ ("비고", "기타 참고사항"),
511
+ ("기관유형", "방문요양/방문목욕/방문간호/주간보호/요양원/공동생활가정 중 선택"),
512
+ ("기관명", "기관명 입력"),
513
+ ]
514
+ for item in guide_items:
515
+ guide_ws.append(item)
516
+
517
+ ws.freeze_panes = "A2"
518
+ ws.sheet_view.showGridLines = False
519
+
520
+ header_fill = PatternFill("solid", fgColor="D9EAD3")
521
+ thin = Side(style="thin", color="999999")
522
+ border = Border(left=thin, right=thin, top=thin, bottom=thin)
523
+ for cell in ws[1]:
524
+ cell.font = Font(name="Malgun Gothic", bold=True)
525
+ cell.fill = header_fill
526
+ cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
527
+ cell.border = border
528
+ for row in ws.iter_rows(min_row=2, max_row=200, min_col=1, max_col=len(headers)):
529
+ for cell in row:
530
+ cell.font = Font(name="Malgun Gothic", size=10)
531
+ cell.alignment = Alignment(vertical="center", wrap_text=True)
532
+ cell.border = border
533
+
534
+ widths = [8, 15, 10, 15, 15, 16, 18, 18, 18, 16, 12, 28, 28, 28, 28, 28, 28, 16, 18, 30, 30, 16, 22]
535
+ for i, width in enumerate(widths, start=1):
536
+ ws.column_dimensions[ws.cell(1, i).column_letter].width = width
537
+
538
+ def add_dropdown_by_idx(col_idx, options):
539
+ letter = ws.cell(1, col_idx).column_letter
540
+ dv = DataValidation(type="list", formula1='"' + ",".join(options) + '"', allow_blank=True)
541
+ ws.add_data_validation(dv)
542
+ dv.add(f"{letter}2:{letter}500")
543
+
544
+ add_dropdown_by_idx(headers.index("성별") + 1, VALID_GENDERS)
545
+ add_dropdown_by_idx(headers.index("장기요양등급") + 1, VALID_GRADES)
546
+ add_dropdown_by_idx(headers.index("이용상태") + 1, VALID_STATUS)
547
+ add_dropdown_by_idx(headers.index("기관유형") + 1, VALID_INST_TYPES)
548
+
549
+ guide_ws.sheet_view.showGridLines = False
550
+ guide_ws.column_dimensions["A"].width = 22
551
+ guide_ws.column_dimensions["B"].width = 90
552
+ for row in guide_ws.iter_rows():
553
+ for cell in row:
554
+ cell.font = Font(name="Malgun Gothic", size=10, bold=(cell.row == 1))
555
+ cell.alignment = Alignment(vertical="center", wrap_text=True)
556
+ cell.border = border
557
+ if cell.row == 1:
558
+ cell.fill = header_fill
559
+
560
+ out = BytesIO()
561
+ wb.save(out)
562
+ out.seek(0)
563
+ return out
564
+
565
+
566
+
567
+
568
+ def validate_client_excel(df):
569
+ errors = []
570
+ df = normalize_excel_columns(df)
571
+ missing = [c for c in REQUIRED_EXCEL_COLUMNS if c not in df.columns]
572
+ if missing:
573
+ errors.append("필수 컬럼 누락: " + ", ".join(missing))
574
+ allowed_cols = set(EXCEL_COLUMNS)
575
+ unknown = [c for c in df.columns if c not in allowed_cols and c != "NO."]
576
+ if unknown:
577
+ errors.append("양식에 없는 컬럼이 있습니다: " + ", ".join(unknown))
578
+ if errors:
579
+ return df, errors
580
+
581
+ for col in EXCEL_COLUMNS:
582
+ if col not in df.columns:
583
+ df[col] = ""
584
+ df = df[EXCEL_COLUMNS].fillna("")
585
+
586
+ for col in DATE_COLUMNS:
587
+ df[col] = df[col].apply(normalize_date_text)
588
+ df["인정번호"] = df["인정번호"].apply(normalize_recognition_number)
589
+ df["실질생일날짜"] = df["실질생일날짜"].apply(normalize_real_birth_date)
590
+
591
+ for idx, row in df.iterrows():
592
+ row_no = idx + 2
593
+ if not safe(row.get("수급자이름")):
594
+ errors.append(f"{row_no}행: 수급자이름은 필수입니다.")
595
+ if safe(row.get("성별")) and safe(row.get("성별")) not in VALID_GENDERS:
596
+ errors.append(f"{row_no}행: 성별은 여/남/기타 중 하나여야 합니다.")
597
+ if safe(row.get("장기요양등급")) and safe(row.get("장기요양등급")) not in VALID_GRADES:
598
+ errors.append(f"{row_no}행: 장기요양등급 값이 올바르지 ���습니다.")
599
+ if safe(row.get("기관유형")) and safe(row.get("기관유형")) not in VALID_INST_TYPES:
600
+ errors.append(f"{row_no}행: 기관유형 값이 올바르지 않습니다.")
601
+ if safe(row.get("이용상태")) and safe(row.get("이용상태")) not in VALID_STATUS:
602
+ errors.append(f"{row_no}행: 이용상태는 이용중/입소중/퇴소/중지/사망 중 하나여야 합니다.")
603
+ for col in DATE_COLUMNS:
604
+ if safe(row.get(col)) and not is_valid_date_text(row.get(col)):
605
+ errors.append(f"{row_no}행: {col}은 2026-03-20 형식으로 입력해야 합니다.")
606
+
607
+ bd = safe(row.get("생년월일"))
608
+ if bd and not (is_valid_date_text(bd) or (len(bd) == 4 and bd.isdigit())):
609
+ errors.append(f"{row_no}행: 생년월일은 1942-09-20 형식 또는 1942 형식으로 입력해야 합니다.")
610
+ return df, errors
611
+
612
+
613
+ def import_clients_from_excel(df, overwrite=False):
614
+ conn = get_conn()
615
+ cur = conn.cursor()
616
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
617
+ inserted = updated = skipped = 0
618
+
619
+ for _, row in df.iterrows():
620
+ data = {db_col: safe(row.get(excel_col)) for excel_col, db_col in EXCEL_TO_DB.items()}
621
+ if not data.get("name"):
622
+ skipped += 1
623
+ continue
624
+ data["recognition_number"] = normalize_recognition_number(data.get("recognition_number"))
625
+ for key in ["recognition_start_date", "recognition_end_date", "admission_date"]:
626
+ data[key] = normalize_date_text(data.get(key))
627
+ data["gender"] = data.get("gender") if data.get("gender") in VALID_GENDERS else "여"
628
+ data["care_grade"] = data.get("care_grade") if data.get("care_grade") in VALID_GRADES else "미입력"
629
+ data["institution_type"] = data.get("institution_type") if data.get("institution_type") in VALID_INST_TYPES else "방문요양"
630
+ data["status"] = data.get("status") if data.get("status") in VALID_STATUS else "이용중"
631
+ data["masked_name"] = mask_name(data.get("name"))
632
+
633
+ # Extract birth_year from birth_date
634
+ birth_date_val = data.get("birth_date")
635
+ birth_year_val = ""
636
+ if birth_date_val:
637
+ birth_date_val = normalize_date_text(birth_date_val)
638
+ data["birth_date"] = birth_date_val
639
+ if len(birth_date_val) >= 4 and birth_date_val[:4].isdigit():
640
+ birth_year_val = birth_date_val[:4]
641
+ data["birth_year"] = birth_year_val
642
+
643
+ if data.get("real_birth_date"):
644
+ data["real_birth_date"] = normalize_real_birth_date(data.get("real_birth_date"))
645
+
646
+ cur.execute("""
647
+ SELECT id FROM clients
648
+ WHERE name=? AND birth_year=? AND institution_name=?
649
+ ORDER BY id DESC LIMIT 1
650
+ """, (data.get("name"), data.get("birth_year"), data.get("institution_name")))
651
+ existing = cur.fetchone()
652
+
653
+ if existing and overwrite:
654
+ client_id = existing[0]
655
+ cur.execute("""
656
+ UPDATE clients SET
657
+ masked_name=?, gender=?, birth_year=?, care_grade=?, previous_care_grade=?,
658
+ recognition_number=?, recognition_start_date=?, recognition_end_date=?,
659
+ institution_type=?, institution_name=?, admission_date=?, main_condition=?,
660
+ cognitive_status=?, mobility_status=?, diet_status=?, toileting_status=?,
661
+ guardian_name=?, guardian_phone=?, notes=?, status=?, updated_at=?,
662
+ birth_date=?, real_birth_date=?, remarks=?
663
+ WHERE id=?
664
+ """, (
665
+ data["masked_name"], data["gender"], data["birth_year"], data["care_grade"], data["care_grade"],
666
+ data["recognition_number"], data["recognition_start_date"], data["recognition_end_date"],
667
+ data["institution_type"], data["institution_name"], data["admission_date"], data["main_condition"],
668
+ data["cognitive_status"], data["mobility_status"], data["diet_status"], data["toileting_status"],
669
+ data["guardian_name"], data["guardian_phone"], data["notes"], data["status"], now,
670
+ data["birth_date"], data["real_birth_date"], data["remarks"], client_id,
671
+ ))
672
+ updated += 1
673
+ elif existing and not overwrite:
674
+ skipped += 1
675
+ else:
676
+ cur.execute("""
677
+ INSERT INTO clients (
678
+ name, masked_name, gender, birth_year, care_grade, previous_care_grade,
679
+ recognition_number, recognition_start_date, recognition_end_date,
680
+ institution_type, institution_name, admission_date,
681
+ main_condition, cognitive_status, mobility_status, diet_status, toileting_status,
682
+ guardian_name, guardian_phone, notes, status,
683
+ plan_change_required, plan_rewrite_status, created_at, updated_at,
684
+ birth_date, real_birth_date, remarks
685
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
686
+ """, (
687
+ data["name"], data["masked_name"], data["gender"], data["birth_year"], data["care_grade"], data["care_grade"],
688
+ data["recognition_number"], data["recognition_start_date"], data["recognition_end_date"],
689
+ data["institution_type"], data["institution_name"], data["admission_date"],
690
+ data["main_condition"], data["cognitive_status"], data["mobility_status"], data["diet_status"], data["toileting_status"],
691
+ data["guardian_name"], data["guardian_phone"], data["notes"], data["status"],
692
+ "아니오", "해당없음", now, now,
693
+ data["birth_date"], data["real_birth_date"], data["remarks"]
694
+ ))
695
+ inserted += 1
696
+ conn.commit()
697
+ conn.close()
698
+ return inserted, updated, skipped
699
+
700
+
701
+ init_db()
702
+
703
+ st.markdown("""
704
+ <style>
705
+ .block-container { padding-top: 2rem; }
706
+ .title-box { background: linear-gradient(135deg, #2E7D32, #66BB6A); padding: 28px; border-radius: 18px; color: white; text-align: center; margin-bottom: 25px; }
707
+ .title-box h1 { margin: 0; font-size: 34px; }
708
+ .title-box p { font-size: 17px; margin-top: 8px; }
709
+ .notice { background: #fff8e1; padding: 15px; border-left: 6px solid #f9a825; border-radius: 10px; margin-bottom: 20px; line-height: 1.65; }
710
+ .okbox { background: #e8f5e9; border-left: 7px solid #43a047; padding: 14px; border-radius: 12px; margin-bottom: 14px; }
711
+ .warnbox { background: #fff3e0; border-left: 7px solid #fb8c00; padding: 14px; border-radius: 12px; margin-bottom: 14px; }
712
+ .dangerbox { background: #ffebee; border-left: 7px solid #e53935; padding: 14px; border-radius: 12px; margin-bottom: 14px; }
713
+ </style>
714
+ """, unsafe_allow_html=True)
715
+
716
+ st.markdown("""
717
+ <div class="title-box">
718
+ <h1>👥 Client Center</h1>
719
+ <p>수급자 등록 / 엑셀 업로드 / 검색 / 수정 / 급여제공계획 재작성 필요 여부 중앙관리</p>
720
+ </div>
721
+ """, unsafe_allow_html=True)
722
+
723
+ display_birthday_alerts()
724
+
725
+ st.markdown("""
726
+ <div class="notice">
727
+ <strong>날짜 입력 안내:</strong> 날짜는 반드시 <strong>2026-03-20</strong> 형식으로 입력해 주세요.<br>
728
+ 인정기간은 한 칸에 쓰지 말고 <strong>인정기간 시작일</strong>과 <strong>인정기간 종료일</strong>을 각각 입력해 주세요.<br>
729
+ 인정번호는 숫자만 입력해도 저장 시 <strong>L</strong>이 자동으로 붙습니다. 예: 1234567890 → L1234567890
730
+ </div>
731
+ """, unsafe_allow_html=True)
732
+
733
+ menu = st.sidebar.radio("메뉴 선택", ["수급자 등록", "엑셀 업로드", "수급자 목록", "수급자 검색", "수정 / 삭제", "급여계획 변경관리", "변경이력 보기"])
734
+
735
+ # -----------------------------
736
+ # 수급자 등록
737
+ # -----------------------------
738
+ if menu == "수급자 등록":
739
+ st.subheader("📝 수급자 직접 등록")
740
+ with st.form("client_form"):
741
+ col1, col2, col3 = st.columns(3)
742
+ with col1:
743
+ name = st.text_input("수급자 이름")
744
+ gender = st.selectbox("성별", VALID_GENDERS)
745
+ birth_date_raw = st.text_input("생년월일", placeholder="예: 1942-09-20 또는 1942")
746
+ with col2:
747
+ care_grade = st.selectbox("장기요양등급", VALID_GRADES)
748
+ recognition_number_raw = st.text_input("인정번호", placeholder="숫자만 입력해도 L 자동 생성")
749
+ institution_type = st.selectbox("기관 유형", VALID_INST_TYPES)
750
+ with col3:
751
+ institution_name = st.text_input("기관명")
752
+ admission_date = st.text_input("이용 시작일 / 입소일", placeholder="예: 2026-03-20")
753
+ status = st.selectbox("상태", VALID_STATUS)
754
+
755
+ col4, col5 = st.columns(2)
756
+ with col4:
757
+ recognition_start_date = st.text_input("인정기간 시작일", placeholder="예: 2025-03-03")
758
+ with col5:
759
+ recognition_end_date = st.text_input("인정기간 종료일", placeholder="예: 2027-03-02")
760
+
761
+ st.markdown("### 건강 및 생활 상태")
762
+ c1, c2 = st.columns(2)
763
+ with c1:
764
+ main_condition = st.text_area("주요 질환 / 상태", placeholder="예: 치매, 고혈압, 당뇨, 낙상위험 등")
765
+ cognitive_status = st.text_area("인지 상태", placeholder="예: 단기기억 저하, 지남력 저하 등")
766
+ mobility_status = st.text_area("이동 상태", placeholder="예: 워커 사용, 부축 필요, 휠체어 사용 등")
767
+ with c2:
768
+ diet_status = st.text_area("식사 상태", placeholder="예: 일반식, 죽식, 연하곤란, 식사보조 필요 등")
769
+ toileting_status = st.text_area("배변 / 배뇨 상태", placeholder="예: 기저귀 착용, 화장실 유도 필요 등")
770
+ notes = st.text_area("특이사항 / 메모")
771
+
772
+ st.markdown("### 생일 및 기타 정보")
773
+ c_b1, c_b2 = st.columns(2)
774
+ with c_b1:
775
+ real_birth_date_raw = st.text_input("실질생일날짜 (옵션)", placeholder="예: 09-20 (생신잔치 알림용)")
776
+ with c_b2:
777
+ remarks = st.text_area("비고")
778
+
779
+ st.markdown("### 보호자 정보")
780
+ c3, c4 = st.columns(2)
781
+ guardian_name = c3.text_input("보호자 이름")
782
+ guardian_phone = c4.text_input("보호자 연락처")
783
+ submitted = st.form_submit_button("등록하기")
784
+
785
+ if submitted:
786
+ errors = []
787
+ if not name:
788
+ errors.append("수급자 이름은 필수입니다.")
789
+
790
+ birth_date = normalize_date_text(birth_date_raw)
791
+ if birth_date_raw and not (is_valid_date_text(birth_date) or (len(birth_date_raw) == 4 and birth_date_raw.isdigit())):
792
+ errors.append("생년월일은 1942-09-20 형식 또는 1942 형식으로 입력해야 합니다.")
793
+
794
+ for label, val in [("인정기간 시작일", recognition_start_date), ("인정기간 종료일", recognition_end_date), ("이용 시작일", admission_date)]:
795
+ val2 = normalize_date_text(val)
796
+ if val2 and not is_valid_date_text(val2):
797
+ errors.append(f"{label}은 2026-03-20 형식으로 입력해 주세요.")
798
+ if errors:
799
+ for err in errors:
800
+ st.error(err)
801
+ else:
802
+ conn = get_conn()
803
+ cur = conn.cursor()
804
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
805
+ recognition_number = normalize_recognition_number(recognition_number_raw)
806
+
807
+ # Extract birth_year
808
+ birth_year = ""
809
+ if birth_date and len(birth_date) >= 4 and birth_date[:4].isdigit():
810
+ birth_year = birth_date[:4]
811
+ elif len(birth_date_raw) == 4 and birth_date_raw.isdigit():
812
+ birth_year = birth_date_raw
813
+
814
+ real_birth_date = normalize_real_birth_date(real_birth_date_raw)
815
+
816
+ cur.execute("""
817
+ INSERT INTO clients (
818
+ name, masked_name, gender, birth_year, care_grade, previous_care_grade,
819
+ recognition_number, recognition_start_date, recognition_end_date,
820
+ institution_type, institution_name, admission_date,
821
+ main_condition, cognitive_status, mobility_status, diet_status, toileting_status,
822
+ guardian_name, guardian_phone, notes, status,
823
+ plan_change_required, plan_rewrite_status, created_at, updated_at,
824
+ birth_date, real_birth_date, remarks
825
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
826
+ """, (
827
+ name, mask_name(name), gender, birth_year, care_grade, care_grade,
828
+ recognition_number, normalize_date_text(recognition_start_date), normalize_date_text(recognition_end_date),
829
+ institution_type, institution_name, normalize_date_text(admission_date),
830
+ main_condition, cognitive_status, mobility_status, diet_status, toileting_status,
831
+ guardian_name, guardian_phone, notes, status,
832
+ "아니오", "해당없음", now, now,
833
+ birth_date, real_birth_date, remarks
834
+ ))
835
+ conn.commit()
836
+ conn.close()
837
+ st.success(f"{mask_name(name)} 수급자가 등록되었습니다. 인정번호: {recognition_number or '미입력'}")
838
+
839
+ # -----------------------------
840
+ # 엑셀 업로드
841
+ # -----------------------------
842
+ elif menu == "엑셀 업로드":
843
+ st.subheader("📥 수급자 엑셀/CSV 업로드")
844
+ st.markdown("""
845
+ <div class="notice">
846
+ <strong>📌 엑셀/CSV 업로드 안내:</strong><br>
847
+ 1. 기본은 <strong>BeeCare 전용 엑셀 양식(.xlsx)</strong>을 사용해 주세요. 엑셀파일을 다운받아 수급자정보를 입력후 업로드해주세요.<br>
848
+ 2. 기관에서 사용하던 엑셀 파일도 업로드할 수 있습니다.<br>
849
+ 3. 업로드가 안 될 경우: 엑셀에서 <strong>[파일] → [다른 이름으로 저장] → [CSV UTF-8] 또는 [쉼표로 구분된 파일]</strong>로 저장한 뒤 업로드해 주세요.<br>
850
+ 4. 그래도 어려우면 <strong>[수급자 직접 등록]</strong>에서 한 분씩 직접 입력하시면 됩니다.<br><br>
851
+ <strong>💡 추가 안내사항:</strong><br>
852
+ - <strong>실질생일날짜</strong>가 있으면 → 그 날짜로 생신잔치 알림이 생성됩니다.<br>
853
+ - <strong>실질생일날짜</strong>가 없으면 → 생년월일의 월/일로 자동 계산됩니다.<br>
854
+ - 실질생일날짜는 <strong>09-20</strong> 형식으로 입력해도 자동으로 올해 날짜로 변환되어 적용됩니다.<br>
855
+ - 기관명과 기관유형은 맨 끝 열에 입력합니다.
856
+ </div>
857
+ """, unsafe_allow_html=True)
858
+ st.download_button("📄 BeeCare 수급자 등록 엑셀 양식 다운로드", data=make_client_excel_template(), file_name="BeeCare_수급자등록양식.xlsx", mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", use_container_width=True)
859
+ uploaded_file = st.file_uploader("작성한 파일 업로드 (XLSX 또는 CSV)", type=["xlsx", "csv"], help="BeeCare 양식의 첫 번째 시트이거나 CSV 형식의 파일을 올려주세요.")
860
+ overwrite = st.checkbox("같은 수급자명 + 출생연도(생년월일의 연도) + 기관명이 이미 있으면 기존 정보를 업데이트", value=False)
861
+ if uploaded_file is not None:
862
+ try:
863
+ if uploaded_file.name.endswith(".csv"):
864
+ try:
865
+ df_raw = pd.read_csv(uploaded_file, dtype=str).dropna(how="all").fillna("")
866
+ except UnicodeDecodeError:
867
+ try:
868
+ uploaded_file.seek(0)
869
+ df_raw = pd.read_csv(uploaded_file, dtype=str, encoding="cp949").dropna(how="all").fillna("")
870
+ except Exception:
871
+ uploaded_file.seek(0)
872
+ df_raw = pd.read_csv(uploaded_file, dtype=str, encoding="euc-kr").dropna(how="all").fillna("")
873
+ else:
874
+ df_raw = pd.read_excel(uploaded_file, dtype=str, sheet_name=0).dropna(how="all").fillna("")
875
+
876
+ df_raw = normalize_excel_columns(df_raw)
877
+ st.markdown("### 업로드 미리보기")
878
+ st.dataframe(df_raw.head(30), use_container_width=True)
879
+ df_valid, errors = validate_client_excel(df_raw)
880
+ if errors:
881
+ st.error("양식 또는 입력값에 문제가 있습니다.")
882
+ for err in errors[:50]:
883
+ st.write("- " + err)
884
+ if len(errors) > 50:
885
+ st.write(f"...외 {len(errors) - 50}건")
886
+ else:
887
+ st.success("검증 완료. 인정번호 L 자동 변환 및 날짜 형식 확인이 완료되었습니다.")
888
+ st.dataframe(df_valid.head(30), use_container_width=True)
889
+ if st.button("✅ 데이터 DB에 저장하기", use_container_width=True):
890
+ inserted, updated, skipped = import_clients_from_excel(df_valid, overwrite=overwrite)
891
+ st.success(f"저장 완료: 신규 {inserted}명 / 업데이트 {updated}명 / 건너뜀 {skipped}명")
892
+ except Exception as e:
893
+ st.error(f"파일을 읽는 중 오류가 발생했습니다: {e}")
894
+
895
+ # -----------------------------
896
+ # 목록
897
+ # -----------------------------
898
+ elif menu == "수급자 목록":
899
+ st.subheader("📋 수급자 목록")
900
+ df = load_clients()
901
+ if df.empty:
902
+ st.info("등록된 수급자가 없습니다.")
903
+ else:
904
+ df = df.copy()
905
+ df["급여계획 알림"] = df["recognition_end_date"].apply(plan_alert_text) if "recognition_end_date" in df.columns else ""
906
+ show_cols = ["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"]
907
+ existing = [c for c in show_cols if c in df.columns]
908
+ st.dataframe(df[existing], use_container_width=True)
909
+ buffer = BytesIO()
910
+ with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
911
+ df[existing].to_excel(writer, index=False, sheet_name="수급자목록")
912
+ buffer.seek(0)
913
+ 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)
914
+
915
+ # -----------------------------
916
+ # 검색
917
+ # -----------------------------
918
+ elif menu == "수급자 검색":
919
+ st.subheader("🔍 수급자 검색")
920
+ keyword = st.text_input("이름, 기관명, 등급, 상태, 인정번호, 변경사유로 검색")
921
+ if keyword:
922
+ conn = get_conn()
923
+ like_keyword = f"%{keyword}%"
924
+ df = pd.read_sql_query("""
925
+ SELECT * FROM clients
926
+ WHERE name LIKE ? OR masked_name LIKE ? OR institution_name LIKE ? OR care_grade LIKE ?
927
+ OR status LIKE ? OR recognition_number LIKE ? OR plan_change_type LIKE ? OR plan_change_reason LIKE ?
928
+ ORDER BY id DESC
929
+ """, conn, params=(like_keyword, like_keyword, like_keyword, like_keyword, like_keyword, like_keyword, like_keyword, like_keyword))
930
+ conn.close()
931
+ if df.empty:
932
+ st.warning("검색 결과가 없습니다.")
933
+ else:
934
+ st.dataframe(df, use_container_width=True)
935
+
936
+ # -----------------------------
937
+ # 수정 / 삭제
938
+ # -----------------------------
939
+ elif menu == "수정 / 삭제":
940
+ st.subheader("✏️ 수급자 정보 수정 / 삭제")
941
+ df = load_clients()
942
+ if df.empty:
943
+ st.info("수정할 수급자가 없습니다.")
944
+ else:
945
+ options = df.apply(lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_name']}", axis=1).tolist()
946
+ selected = st.selectbox("수정할 수급자 선택", options)
947
+ selected_id = int(selected.split("번")[0])
948
+ c = df[df["id"] == selected_id].iloc[0]
949
+ with st.form("edit_form"):
950
+ col1, col2, col3 = st.columns(3)
951
+ with col1:
952
+ name = st.text_input("수급자 이름", value=safe(c.get("name")))
953
+ gender = st.selectbox("성별", VALID_GENDERS, index=VALID_GENDERS.index(safe(c.get("gender"))) if safe(c.get("gender")) in VALID_GENDERS else 0)
954
+ birth_date_raw = st.text_input("생년월일", value=safe(c.get("birth_date")), placeholder="예: 1942-09-20 또는 1942")
955
+ with col2:
956
+ old_grade = safe(c.get("care_grade"))
957
+ care_grade = st.selectbox("장기요양등급", VALID_GRADES, index=VALID_GRADES.index(old_grade) if old_grade in VALID_GRADES else 7)
958
+ recognition_number = st.text_input("인정번호", value=safe(c.get("recognition_number")), help="숫자만 입력해도 L이 자동으로 붙습니다.")
959
+ 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)
960
+ with col3:
961
+ institution_name = st.text_input("기관명", value=safe(c.get("institution_name")))
962
+ admission_date = st.text_input("이용 시작일 / 입소일", value=safe(c.get("admission_date")), placeholder="예: 2026-03-20")
963
+ status = st.selectbox("상태", VALID_STATUS, index=VALID_STATUS.index(safe(c.get("status"))) if safe(c.get("status")) in VALID_STATUS else 0)
964
+
965
+ col4, col5 = st.columns(2)
966
+ recognition_start_date = col4.text_input("인정기간 시작일", value=safe(c.get("recognition_start_date")), placeholder="예: 2025-03-03")
967
+ recognition_end_date = col5.text_input("인정기간 종료일", value=safe(c.get("recognition_end_date")), placeholder="예: 2027-03-02")
968
+
969
+ main_condition = st.text_area("주요 질환 / 상태", value=safe(c.get("main_condition")))
970
+ cognitive_status = st.text_area("인지 상태", value=safe(c.get("cognitive_status")))
971
+ mobility_status = st.text_area("이동 상태", value=safe(c.get("mobility_status")))
972
+ diet_status = st.text_area("식사 상태", value=safe(c.get("diet_status")))
973
+ toileting_status = st.text_area("배변 / 배뇨 상태", value=safe(c.get("toileting_status")))
974
+ guardian_name = st.text_input("보호자 이름", value=safe(c.get("guardian_name")))
975
+ guardian_phone = st.text_input("보호자 연락처", value=safe(c.get("guardian_phone")))
976
+ notes = st.text_area("특이사항 / 메모", value=safe(c.get("notes")))
977
+
978
+ st.markdown("### 생일 및 기타 정보")
979
+ c_b1, c_b2 = st.columns(2)
980
+ real_birth_date_raw = c_b1.text_input("실질생일날짜 (옵션)", value=safe(c.get("real_birth_date")), placeholder="예: 09-20 (생신잔치 알림용)")
981
+ remarks = c_b2.text_area("비고", value=safe(c.get("remarks")))
982
+
983
+ save_btn = st.form_submit_button("수정 저장")
984
+ if save_btn:
985
+ errors = []
986
+ birth_date = normalize_date_text(birth_date_raw)
987
+ if birth_date_raw and not (is_valid_date_text(birth_date) or (len(birth_date_raw) == 4 and birth_date_raw.isdigit())):
988
+ errors.append("생년월일은 1942-09-20 형식 또는 1942 형식으로 입력해야 합니다.")
989
+ for label, val in [("인정기간 시작일", recognition_start_date), ("인정기간 종료일", recognition_end_date), ("이용 시작일", admission_date)]:
990
+ val2 = normalize_date_text(val)
991
+ if val2 and not is_valid_date_text(val2):
992
+ errors.append(f"{label}은 2026-03-20 형식으로 입력해 주세요.")
993
+ if errors:
994
+ for err in errors:
995
+ st.error(err)
996
+ else:
997
+ conn = get_conn()
998
+ cur = conn.cursor()
999
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1000
+ detected_required = safe(c.get("plan_change_required"), "아니오")
1001
+ detected_type = safe(c.get("plan_change_type"))
1002
+ detected_reason = safe(c.get("plan_change_reason"))
1003
+ detected_date = safe(c.get("plan_change_date"))
1004
+ detected_status = safe(c.get("plan_rewrite_status"), "해당없음")
1005
+ if old_grade and care_grade != old_grade:
1006
+ detected_required, detected_status, auto_memo = calculate_plan_change("등급변경", f"{old_grade}에서 {care_grade}로 변경", status)
1007
+ detected_type = "등급변경"
1008
+ detected_reason = f"장기요양등급 변경: {old_grade} → {care_grade}"
1009
+ detected_date = str(date.today())
1010
+ 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)
1011
+
1012
+ # Extract birth_year
1013
+ birth_year = ""
1014
+ if birth_date and len(birth_date) >= 4 and birth_date[:4].isdigit():
1015
+ birth_year = birth_date[:4]
1016
+ elif len(birth_date_raw) == 4 and birth_date_raw.isdigit():
1017
+ birth_year = birth_date_raw
1018
+
1019
+ real_birth_date = normalize_real_birth_date(real_birth_date_raw)
1020
+
1021
+ cur.execute("""
1022
+ UPDATE clients SET name=?, masked_name=?, gender=?, birth_year=?, care_grade=?, previous_care_grade=?,
1023
+ recognition_number=?, recognition_start_date=?, recognition_end_date=?,
1024
+ institution_type=?, institution_name=?, admission_date=?, main_condition=?, cognitive_status=?, mobility_status=?,
1025
+ diet_status=?, toileting_status=?, guardian_name=?, guardian_phone=?, notes=?, status=?,
1026
+ plan_change_required=?, plan_change_type=?, plan_change_reason=?, plan_change_date=?, plan_rewrite_status=?, updated_at=?,
1027
+ birth_date=?, real_birth_date=?, remarks=?
1028
+ WHERE id=?
1029
+ """, (
1030
+ name, mask_name(name), gender, birth_year, care_grade, old_grade,
1031
+ normalize_recognition_number(recognition_number), normalize_date_text(recognition_start_date), normalize_date_text(recognition_end_date),
1032
+ institution_type, institution_name, normalize_date_text(admission_date), main_condition, cognitive_status, mobility_status,
1033
+ diet_status, toileting_status, guardian_name, guardian_phone, notes, status,
1034
+ detected_required, detected_type, detected_reason, detected_date, detected_status, now,
1035
+ birth_date, real_birth_date, remarks, selected_id,
1036
+ ))
1037
+ conn.commit()
1038
+ conn.close()
1039
+ st.success("수급자 정보가 수정되었습니다.")
1040
+ st.divider()
1041
+ if st.button("⚠️ 이 수급자 삭제하기"):
1042
+ conn = get_conn()
1043
+ cur = conn.cursor()
1044
+ cur.execute("DELETE FROM clients WHERE id = ?", (selected_id,))
1045
+ conn.commit()
1046
+ conn.close()
1047
+ st.warning("수급자 정보가 삭제되었습니다.")
1048
+
1049
+ # -----------------------------
1050
+ # 급여계획 변경관리
1051
+ # -----------------------------
1052
+ elif menu == "급여계획 변경관리":
1053
+ st.subheader("🔁 급여제공계획 재작성 필요 여부 관리")
1054
+ df = load_clients()
1055
+ if df.empty:
1056
+ st.info("등록된 수급자가 없습니다.")
1057
+ else:
1058
+ options = df.apply(lambda x: f"{x['id']}번 - {x['masked_name']} / {x['care_grade']} / {x['institution_type']} / {x['status']}", axis=1).tolist()
1059
+ selected = st.selectbox("수급자 선택", options)
1060
+ selected_id = int(selected.split("번")[0])
1061
+ c = df[df["id"] == selected_id].iloc[0]
1062
+ st.markdown("### 현재 상태")
1063
+ m1, m2, m3, m4, m5 = st.columns(5)
1064
+ m1.metric("수급자", safe(c.get("masked_name")))
1065
+ m2.metric("등급", safe(c.get("care_grade")))
1066
+ m3.metric("기관유형", safe(c.get("institution_type")))
1067
+ m4.metric("재작성 필요", safe(c.get("plan_change_required"), "아니오"))
1068
+ m5.metric("인정기간 알림", plan_alert_text(safe(c.get("recognition_end_date"))))
1069
+ current_required = safe(c.get("plan_change_required"), "아니오")
1070
+ if current_required == "예":
1071
+ st.markdown(f'<div class="dangerbox"><strong>급여제공계획 재작성 필요:</strong> {safe(c.get("plan_change_reason"))}</div>', unsafe_allow_html=True)
1072
+ else:
1073
+ st.markdown(f'<div class="okbox"><strong>현재 상태:</strong> {safe(c.get("plan_rewrite_status"), "해당없음")}</div>', unsafe_allow_html=True)
1074
+
1075
+ st.markdown("### 변경사유 입력")
1076
+ inst = safe(c.get("institution_type"), "방문요양")
1077
+ reason_options = institution_change_reasons(inst)
1078
+ col1, col2, col3 = st.columns(3)
1079
+ change_type = col1.selectbox("변경유형", ["상태변화", "등급변경", "보호자 요청", "서비스 변경", "욕구사정 결과", "상담일지 결과", "사례관리 결과", "결과평가 반영", "병원입원", "퇴원 후 재이용", "전원", "사망", "계약해지", "서비스 종료", "기타"])
1080
+ change_reason_preset = col2.selectbox("기관유형별 변경사유", reason_options)
1081
+ change_date = col3.date_input("발생일 / 확인일", value=date.today())
1082
+ linked_document = st.multiselect("연동 근거 문서", ["상담일지", "욕구사정", "사례관리", "급여제공 결과평가", "상태변화기록지", "보호자 상담", "공단 인정서", "병원진료/입퇴원 서류", "기타"], default=["상담일지"])
1083
+ detail_reason = st.text_area("세부 변경사유", value=f"{change_reason_preset} 관련 상태변화 또는 서비스 조정 필요성 확인", height=100)
1084
+ required, rewrite_status, memo = calculate_plan_change(change_type, detail_reason, safe(c.get("status")))
1085
+ r1, r2, r3 = st.columns(3)
1086
+ r1.metric("재작성 필요 여부", required)
1087
+ r2.metric("처리상태", rewrite_status)
1088
+ r3.metric("근거문서", ", ".join(linked_document))
1089
+ st.warning(memo) if required == "예" else st.info(memo)
1090
+ if st.button("💾 변경사유 저장 및 수급자 상태 반영", use_container_width=True):
1091
+ 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)
1092
+ st.success("변경사유가 저장되었고 Client Center에 반영되었습니다.")
1093
+ st.markdown("### 이 수급자의 변경이력")
1094
+ logs = load_change_logs(selected_id)
1095
+ st.dataframe(logs, use_container_width=True) if not logs.empty else st.info("저장된 변경이력이 없습니다.")
1096
+
1097
+ # -----------------------------
1098
+ # 변경이력 보기
1099
+ # -----------------------------
1100
+ elif menu == "변경이력 보기":
1101
+ st.subheader("📚 전체 급여제공계획 변경이력")
1102
+ logs = load_change_logs()
1103
+ st.dataframe(logs, use_container_width=True) if not logs.empty else st.info("저장된 변경이력이 없습니다.")