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

Upload app.py

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