devorah-ai-2016 commited on
Commit
7da99e7
·
verified ·
1 Parent(s): 1023020

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -774
app.py DELETED
@@ -1,774 +0,0 @@
1
- import os
2
- import sqlite3
3
- import random
4
- import tempfile
5
- from io import BytesIO
6
- from datetime import date, datetime
7
-
8
- import pandas as pd
9
- import streamlit as st
10
- from openpyxl import Workbook
11
- from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
12
- from openpyxl.utils import get_column_letter
13
- from openpyxl.drawing.image import Image as XLImage
14
- from openpyxl.worksheet.pagebreak import Break # 페이지 나누기 기능 추가
15
-
16
-
17
- # =========================================================
18
- # 급여제공지침 교육일지 통합연동 생성기
19
- # - Client Center DB와 같은 clients.db 사용
20
- # - 기관정보/참석자(직종별 입력)/강사/교육자료 첨부/교육결과
21
- # - 평가 적합도, 후속조치는 자체 보관용 (엑셀 출력 제외)
22
- # - 결재라인 담당자/시설장 2칸, 지저분한 빈칸 없이 출력
23
- # - 교육내용과 교육결과 페이지 분할
24
- # =========================================================
25
-
26
- st.set_page_config(
27
- page_title="급여제공지침 교육일지",
28
- page_icon="📘",
29
- layout="wide"
30
- )
31
-
32
- CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
33
-
34
- DB_CANDIDATES = [
35
- os.path.join(CURRENT_DIR, "data", "clients.db"),
36
- os.path.join(CURRENT_DIR, "..", "Client Center", "data", "clients.db"),
37
- os.path.join(CURRENT_DIR, "..", "ClientCenter", "data", "clients.db"),
38
- os.path.join(CURRENT_DIR, "..", "Client_Center", "data", "clients.db"),
39
- ]
40
-
41
- DB_PATH = None
42
- for p in DB_CANDIDATES:
43
- if os.path.exists(p):
44
- DB_PATH = p
45
- break
46
-
47
- if DB_PATH is None:
48
- os.makedirs(os.path.join(CURRENT_DIR, "data"), exist_ok=True)
49
- DB_PATH = os.path.join(CURRENT_DIR, "data", "clients.db")
50
-
51
-
52
- # -----------------------------
53
- # 디자인
54
- # -----------------------------
55
- st.markdown("""
56
- <style>
57
- .block-container { padding-top: 2rem; }
58
- .hero {
59
- background: linear-gradient(135deg, #7C2D12, #EA580C);
60
- padding: 30px;
61
- border-radius: 22px;
62
- text-align: center;
63
- margin-bottom: 22px;
64
- }
65
- .hero h1 { color: white; margin: 0; font-size: 36px; }
66
- .hero p { color: white; margin-top: 10px; font-size: 18px; }
67
- .notice {
68
- background: #fff8e1;
69
- border-left: 7px solid #f9a825;
70
- padding: 15px;
71
- border-radius: 12px;
72
- margin-bottom: 18px;
73
- }
74
- .okbox {
75
- background: #e8f5e9;
76
- border-left: 7px solid #43a047;
77
- padding: 14px;
78
- border-radius: 12px;
79
- margin-bottom: 14px;
80
- }
81
- .warnbox {
82
- background: #fff3e0;
83
- border-left: 7px solid #fb8c00;
84
- padding: 14px;
85
- border-radius: 12px;
86
- margin-bottom: 14px;
87
- }
88
- </style>
89
- """, unsafe_allow_html=True)
90
-
91
- st.markdown("""
92
- <div class="hero">
93
- <h1>📘 급여제공지침 교육일지 생성기</h1>
94
- <p>종사자 급여제공지침 교육일지를 생성하고 직종별 참석 명단과 이수기록을 관리합니다.</p>
95
- </div>
96
- """, unsafe_allow_html=True)
97
-
98
- st.markdown("""
99
- <div class="notice">
100
- <strong>필수 구조:</strong> 교육명, 교육일시, 장소, 강사명, 직종별 참석자 명단, 교육목적, 교육내용, 교육자료 첨부, 교육결과 등을 포함합니다.
101
- </div>
102
- """, unsafe_allow_html=True)
103
-
104
-
105
- # -----------------------------
106
- # DB
107
- # -----------------------------
108
- def get_conn():
109
- return sqlite3.connect(DB_PATH, check_same_thread=False)
110
-
111
- def init_db():
112
- conn = get_conn()
113
- cur = conn.cursor()
114
-
115
- cur.execute("""
116
- CREATE TABLE IF NOT EXISTS education_records (
117
- id INTEGER PRIMARY KEY AUTOINCREMENT,
118
- institution_name TEXT,
119
- institution_type TEXT,
120
- education_title TEXT,
121
- guideline_items TEXT,
122
- education_date TEXT,
123
- education_time TEXT,
124
- education_place TEXT,
125
- instructor_name TEXT,
126
- instructor_position TEXT,
127
- attendees TEXT,
128
- absent_staff TEXT,
129
- education_method TEXT,
130
- education_purpose TEXT,
131
- education_content TEXT,
132
- education_materials TEXT,
133
- education_result TEXT,
134
- followup_plan TEXT,
135
- evaluation_score INTEGER,
136
- missing_items TEXT,
137
- compliance_result TEXT,
138
- created_at TEXT
139
- )
140
- """)
141
-
142
- conn.commit()
143
- conn.close()
144
-
145
- def save_education_record(data):
146
- conn = get_conn()
147
- cur = conn.cursor()
148
- cur.execute("""
149
- INSERT INTO education_records (
150
- institution_name, institution_type, education_title, guideline_items,
151
- education_date, education_time, education_place,
152
- instructor_name, instructor_position, attendees, absent_staff,
153
- education_method, education_purpose, education_content,
154
- education_materials, education_result, followup_plan,
155
- evaluation_score, missing_items, compliance_result, created_at
156
- )
157
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
158
- """, (
159
- data["institution_name"], data["institution_type"], data["education_title"],
160
- data["guideline_items"], data["education_date"], data["education_time"],
161
- data["education_place"], data["instructor_name"], data["instructor_position"],
162
- data["attendees"], data["absent_staff"], data["education_method"],
163
- data["education_purpose"], data["education_content"], data["education_materials"],
164
- data["education_result"], data["followup_plan"], data["evaluation_score"],
165
- data["missing_items"], data["compliance_result"], datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
166
- ))
167
- conn.commit()
168
- conn.close()
169
-
170
- def load_education_records():
171
- conn = get_conn()
172
- try:
173
- df = pd.read_sql_query("SELECT * FROM education_records ORDER BY id DESC", conn)
174
- except Exception:
175
- df = pd.DataFrame()
176
- conn.close()
177
- return df
178
-
179
- init_db()
180
-
181
-
182
- # -----------------------------
183
- # 급여제공지침
184
- # -----------------------------
185
- GUIDELINES = {
186
- "01. 종사자 윤리지침": {
187
- "purpose": "종사자의 직업윤리와 수급자 존중 태도를 강화하여 전문적인 급여제공이 이루어지도록 한다.",
188
- "content": ["수급자 인격 존중과 사생활 보호", "급여제공 범위 준수와 부당요구 대응", "전문직 종사자로서의 책임과 보고체계", "서비스 제공 중 비밀유지와 공정한 태도"],
189
- },
190
- "02. 노인인권보호지침": {
191
- "purpose": "수급자의 권리와 자기결정권을 존중하고 인권침해를 예방한다.",
192
- "content": ["노인 인권의 기본 원칙", "신체적·정서적·언어적 인권침해 예방", "수급자의 의사표현과 선택권 존중", "인권침해 발생 시 보고 및 조치 절차"],
193
- },
194
- "03. 노인학대예방지침": {
195
- "purpose": "노인학대 유형을 이해하고 의심사례 발견 시 즉시 보고할 수 있도록 한다.",
196
- "content": ["신체적·정서적·경제적 학대 및 방임의 유형", "학대 의심 징후 확인", "신고의무와 신고절차", "학대 예방을 위한 종사자 행동수칙"],
197
- },
198
- "04. 개인정보보호지침": {
199
- "purpose": "수급자와 보호자의 개인정보를 안전하게 관리하고 유출을 예방한다.",
200
- "content": ["개인정보 수집·이용·보관 원칙", "문서 및 전산자료 접근관리", "사진·영상 사용 시 동의와 보호조치", "개인정보 유출 시 보고 절차"],
201
- },
202
- "05. 성폭력예방 및 대응지침": {
203
- "purpose": "수급자와 종사자의 성적 자기결정권을 보호하고 성희롱·성폭력을 예방한다.",
204
- "content": ["성희롱·성폭력의 개념과 사례", "목욕·배변·신체지원 시 유의사항", "불쾌감 표현 시 즉시 중단 및 보고", "피해 발생 시 보호조치와 보고체계"],
205
- },
206
- "06. 응급상황대응지침": {
207
- "purpose": "낙상, 호흡곤란, 의식저하 등 응급상황 발생 시 신속하고 적절하게 대응한다.",
208
- "content": ["응급상황 유형과 초기 확인", "119 신고 및 보호자 연락 절차", "기관 보고체계와 기록 방법", "심폐소생술 및 기본 응급처치 유의사항"],
209
- },
210
- "07. 감염예방 및 관리지침": {
211
- "purpose": "감염병 전파를 예방하고 수급자와 종사자의 건강을 보호한다.",
212
- "content": ["손위생과 개인보호구 사용", "발열·호흡기 증상 확인과 격리 안내", "환경소독 및 환기관리", "감염 의심 시 보고 및 조치"],
213
- },
214
- "08. 욕창예방지침": {
215
- "purpose": "욕창 위험요인을 조기에 발견하고 체위변경과 피부관찰을 통해 욕창을 예방한다.",
216
- "content": ["욕창 위험요인과 호발부위", "체위변경과 압박 완화", "피부 발적·상처 관찰 및 보고", "영양·수분섭취와 청결관리"],
217
- },
218
- "09. 낙상예방지침": {
219
- "purpose": "수급자의 낙상 위험을 줄이고 안전한 이동과 생활환경을 유지한다.",
220
- "content": ["낙상 위험요인 확인", "보행보조와 화장실 이동 지원", "환경정리와 미끄럼 예방", "낙상 발생 시 조치와 기록"],
221
- },
222
- "10. 치매예방 및 관리지침": {
223
- "purpose": "인지기능 저하 수급자의 특성을 이해하고 안정적인 돌봄을 제공한다.",
224
- "content": ["치매 증상과 행동심리증상 이해", "반복설명과 안정적 환경 제공", "인지활동과 일상생활 지원", "배회·불안·공격성 대응 방법"],
225
- },
226
- "11. 근골격계질환 예방지침": {
227
- "purpose": "종사자의 허리·어깨·손목 손상을 예방하고 안전한 업무수행 방법을 익힌다.",
228
- "content": ["근골격계질환 위험요인", "이동·체위변경 시 올바른 자세", "보조도구 활용과 2인 협조", "통증 발생 시 보고와 업무조정"],
229
- },
230
- "12. 종사자 인권침해 예방지침": {
231
- "purpose": "종사자에 대한 폭언·폭행·성희롱 등 인권침해를 예방하고 보호체계를 이해한다.",
232
- "content": ["종사자 인권침해 유형", "부당요구와 폭언·폭행 대응", "고충 접수와 기관 보호조치", "재발방지를 위한 기록과 보고"],
233
- },
234
- "13. 고충처리 및 야간근무지침": {
235
- "purpose": "수급자·보호자·종사자 고충을 체계적으로 처리하고 야간근무 시 안전관리 원칙을 준수한다.",
236
- "content": ["고충 접수와 처리 절차", "민원 예방과 상담기록 관리", "야간근무 시 순찰·응급상황 대응", "야간 특이사항 보고 및 인수인계"],
237
- },
238
- }
239
-
240
- METHODS = ["집합교육", "개별교육", "온라인교육", "회의교육", "자료배포 후 확인", "현장실습 병행"]
241
-
242
-
243
- # -----------------------------
244
- # 생성 로직
245
- # -----------------------------
246
- def build_education_text(selected_items, institution_type, method, custom_content):
247
- if not selected_items:
248
- return "", ""
249
-
250
- purpose_lines = []
251
- content_lines = []
252
- for item in selected_items:
253
- g = GUIDELINES[item]
254
- purpose_lines.append(f"- {item}: {g['purpose']}")
255
- content_lines.append(f"[{item}]")
256
- for c in g["content"]:
257
- content_lines.append(f"- {c}")
258
- content_lines.append("")
259
-
260
- institution_note = {
261
- "방문요양": "방문서비스 현장에서 단독 근무 중 발생할 수 있는 응급상황, 개인정보보호, 보호자 요청 대응을 중심으로 교육함.",
262
- "방문목욕": "목욕지원 과정에서 신체노출, 낙상, 피부상태 확인, 감염예방, 응급상황 대응을 중심으로 교육함.",
263
- "방문간호": "건강상태 관찰, 감염관리, 개인정보보호, 의료연계 및 응급상황 대응을 중심으로 교육함.",
264
- "주간보호": "센터 내 단체생활, 프로그램 참여, 송영안전, 낙상·감염예방, 수급자 간 갈등 예방을 중심으로 교육함.",
265
- "요양원": "입소생활 전반의 인권보호, 욕창·낙상·감염예방, 야간근무, 응급상황 대응을 중심으로 교육함.",
266
- "공동생활가정": "소규모 공동생활 중 인권보호, 정서지원, 야간안전, 감염예방, 고충처리를 중심으로 교육함.",
267
- }.get(institution_type, "")
268
-
269
- purpose = "교육 목적\n" + "\n".join(purpose_lines)
270
-
271
- content = f"""
272
- [교육방법]
273
- {method}
274
-
275
- [기관유형별 교육 중점]
276
- {institution_note}
277
-
278
- [교육내용]
279
- {chr(10).join(content_lines)}
280
-
281
- [기관 추가 교육내용]
282
- {custom_content or '기관 운영규정과 종사자 업무수칙에 따라 실제 사례 중심으로 교육을 진행함.'}
283
- """.strip()
284
-
285
- return purpose, content
286
-
287
-
288
- def build_result_text(selected_items, att_dict, absent_staff, method):
289
- item_text = ", ".join(selected_items)
290
-
291
- # 이름 갯수 대략적 카운트 (쉼표나 띄어쓰기 기준)
292
- total_names = 0
293
- for names in att_dict.values():
294
- total_names += len([n for n in names.replace(',', ' ').split() if n.strip()])
295
-
296
- absent_text = absent_staff.strip() or "미참석자 없음"
297
-
298
- variants = [
299
- f"{item_text} 교육을 통해 종사자의 지침 이해도를 높이고 실제 급여제공 과정에서 준수해야 할 보고체계와 행동수칙을 재확인하였다.",
300
- f"참석자들은 {item_text}의 주요 내용을 확인하였으며, 수급자 안전과 권리보호를 위한 실천방법을 공유하였다.",
301
- f"교육 후 질의응답을 통해 현장에서 발생할 수 있는 사례를 점검하였고, 지침 미준수 예방과 기록관리의 중요성을 확인하였다.",
302
- ]
303
-
304
- return f"""
305
- 교육결과, 총 {total_names}명의 종사자가 {method} 방식으로 교육에 참여하였다.
306
- {random.choice(variants)}
307
-
308
- 참석자 전원이 교육내용을 잘 숙지하였으며, 교육자료에 제시된 지침 내용을 실제 급여제공 과정에서 준수하기로 하였다.
309
- 기관은 급여제공지침 교육자료를 종사자가 쉽게 확인할 수 있는 장소에 공개 게시하고, 종사자가 수시로 지침 내용을 확인하여 급여제공에 반영할 수 있도록 관리한다.
310
- 또한 신규직원, 미참석자, 지침 숙지가 부족한 종사자에게는 보충교육을 실시하고, 교육내용이 현장에서 이행되는지 지속적으로 모니터링한다.
311
-
312
- 미참석자 관리: {absent_text}
313
- """.strip()
314
-
315
-
316
- def evaluate_education(data):
317
- required = {
318
- "교육명": bool(data["education_title"].strip()),
319
- "교육일시": bool(data["education_date"]) and bool(data["education_time"].strip()),
320
- "교육장소": bool(data["education_place"].strip()),
321
- "강사명": bool(data["instructor_name"].strip()),
322
- "교육대상/참석자": bool(data["attendees"].strip()),
323
- "교육지침 선택": bool(data["guideline_items"].strip()),
324
- "교육목적": bool(data["education_purpose"].strip()),
325
- "교육내용": bool(data["education_content"].strip()),
326
- "교육자료 ��부/명시": bool(data["education_materials"].strip()),
327
- "교육결과": bool(data["education_result"].strip()),
328
- "미참석자 관리": "미참석" in data["education_result"] or bool(data["absent_staff"].strip()),
329
- "후속조치": bool(data["followup_plan"].strip()),
330
- }
331
-
332
- score = int(sum(required.values()) / len(required) * 100)
333
- missing = [k for k, v in required.items() if not v]
334
-
335
- if score >= 90:
336
- result = "평가 적합도가 높습니다. 교육일시, 강사, 참석자, 교육내용, 결과 및 후속조치가 잘 반영되었습니다."
337
- elif score >= 75:
338
- result = "대체로 적합하나 일부 보완이 필요합니다. 부족 항목을 보완하면 평가 대응력이 높아집니다."
339
- else:
340
- result = "보완이 필요합니다. 참석자 명단, 교육자료, 교육결과, 미참석자 관리가 구체적으로 들어가야 합니다."
341
-
342
- return score, missing, result
343
-
344
-
345
- def save_uploaded_materials(uploaded_files):
346
- paths = []
347
- names = []
348
- for file in (uploaded_files or [])[:3]:
349
- suffix = os.path.splitext(file.name)[1].lower() or ".png"
350
- temp_path = os.path.join(tempfile.gettempdir(), f"edu_material_{datetime.now().strftime('%Y%m%d%H%M%S%f')}{suffix}")
351
- with open(temp_path, "wb") as f:
352
- f.write(file.getbuffer())
353
- paths.append(temp_path)
354
- names.append(file.name)
355
- return paths, names
356
-
357
-
358
- # -----------------------------
359
- # 엑셀 출력 (디자인 선명화 및 셀 잘림 방지)
360
- # -----------------------------
361
- def style_range(ws, cell_range, border_on=True, fill=None, font=None, alignment=None):
362
- """병합 셀 포함 범위 전체에 스타일 적용 (검정색 테두리로 선명하게)"""
363
- thin = Side(style="thin", color="000000")
364
- border = Border(left=thin, right=thin, top=thin, bottom=thin)
365
-
366
- cells = ws[cell_range]
367
- if not isinstance(cells, tuple):
368
- cells = ((cells,),)
369
-
370
- for row in cells:
371
- for cell in row:
372
- if border_on:
373
- cell.border = border
374
- if fill:
375
- cell.fill = fill
376
- if font:
377
- cell.font = font
378
- if alignment:
379
- cell.alignment = alignment
380
-
381
- def write_title_with_approval(ws, title, title_fill, header_fill):
382
- for col in range(1, 10):
383
- ws.column_dimensions[get_column_letter(col)].width = 11.5
384
-
385
- ws.merge_cells("A1:G2")
386
- c = ws.cell(1, 1)
387
- c.value = title
388
- c.font = Font(name="Malgun Gothic", size=24, bold=True)
389
- c.alignment = Alignment(horizontal="center", vertical="center")
390
- style_range(ws, "A1:G2", fill=title_fill)
391
-
392
- # 결재라인 (우측 상단 2칸) 지저분한 선 방지를 위해 셀별로 스타일 지정
393
- ws.cell(1, 8).value = "담당자"
394
- ws.cell(1, 9).value = "시설장"
395
- ws.cell(2, 8).value = ""
396
- ws.cell(2, 9).value = ""
397
-
398
- for rr in [1, 2]:
399
- for cc in [8, 9]:
400
- cell = ws.cell(rr, cc)
401
- cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
402
- if rr == 1:
403
- cell.font = Font(name="Malgun Gothic", size=11, bold=True)
404
- cell.fill = header_fill
405
- else:
406
- cell.font = Font(name="Malgun Gothic", size=11)
407
-
408
- # 셀 단위로만 선명하게 테두리를 긋습니다.
409
- cell_name = f"{get_column_letter(cc)}{rr}"
410
- style_range(ws, f"{cell_name}:{cell_name}")
411
-
412
- ws.row_dimensions[1].height = 28
413
- ws.row_dimensions[2].height = 42
414
-
415
- def write_info_row(ws, row, a, b, c, d, e, f, header_fill):
416
- ws.cell(row, 1).value = a
417
- ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=3)
418
- ws.cell(row, 2).value = b
419
-
420
- ws.cell(row, 4).value = c
421
- ws.merge_cells(start_row=row, start_column=5, end_row=row, end_column=6)
422
- ws.cell(row, 5).value = d
423
-
424
- ws.cell(row, 7).value = e
425
- ws.merge_cells(start_row=row, start_column=8, end_row=row, end_column=9)
426
- ws.cell(row, 8).value = f
427
-
428
- for col in [1, 4, 7]:
429
- ws.cell(row, col).fill = header_fill
430
- ws.cell(row, col).font = Font(name="Malgun Gothic", size=11, bold=True)
431
- ws.cell(row, col).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
432
-
433
- for col in [2, 5, 8]:
434
- ws.cell(row, col).font = Font(name="Malgun Gothic", size=11)
435
- ws.cell(row, col).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
436
-
437
- style_range(ws, f"A{row}:I{row}")
438
- ws.row_dimensions[row].height = 30
439
-
440
- def write_attendee_row(ws, row, k1, v1, k2, v2, k3, v3, header_fill):
441
- """참석자 명단 전용 3열 분할 구조 (직종 | 이름 | 직종 | 이름 | 직종 | 이름)"""
442
- ws.cell(row, 1).value = k1
443
- ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=3)
444
- ws.cell(row, 2).value = v1
445
-
446
- ws.cell(row, 4).value = k2
447
- ws.merge_cells(start_row=row, start_column=5, end_row=row, end_column=6)
448
- ws.cell(row, 5).value = v2
449
-
450
- ws.cell(row, 7).value = k3
451
- ws.merge_cells(start_row=row, start_column=8, end_row=row, end_column=9)
452
- ws.cell(row, 8).value = v3
453
-
454
- for c in [1, 4, 7]:
455
- ws.cell(row, c).fill = header_fill
456
- ws.cell(row, c).font = Font(name="Malgun Gothic", size=11, bold=True)
457
- ws.cell(row, c).alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
458
-
459
- for c in [2, 5, 8]:
460
- ws.cell(row, c).font = Font(name="Malgun Gothic", size=11)
461
- ws.cell(row, c).alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
462
-
463
- style_range(ws, f"A{row}:I{row}")
464
-
465
- # 가독성을 높이고 문장이 잘리지 않도록 여유 높이 계산
466
- max_len = max(len(str(v1)), len(str(v2)), len(str(v3)))
467
- lines = (max_len // 15) + 1
468
- ws.row_dimensions[row].height = max(35, lines * 22 + 20)
469
-
470
-
471
- def write_section(ws, row, title, content, header_fill, min_height=100):
472
- # 제목 행
473
- ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
474
- t_cell = ws.cell(row, 1)
475
- t_cell.value = title
476
- t_cell.font = Font(name="Malgun Gothic", size=15, bold=True)
477
- t_cell.alignment = Alignment(horizontal="center", vertical="center")
478
- t_cell.fill = header_fill
479
- style_range(ws, f"A{row}:I{row}")
480
- ws.row_dimensions[row].height = 30
481
- row += 1
482
-
483
- # 내용 행
484
- ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=9)
485
- c_cell = ws.cell(row, 1)
486
- c_cell.value = content
487
- c_cell.font = Font(name="Malgun Gothic", size=11)
488
- c_cell.alignment = Alignment(horizontal="left", vertical="top", wrap_text=True)
489
- style_range(ws, f"A{row}:I{row}")
490
-
491
- # 줄바꿈과 텍스트 길이에 비례해 셀 높이 정밀 계산 (여유 간격 확대)
492
- content_str = str(content)
493
- lines = 0
494
- for line in content_str.split("\n"):
495
- lines += (len(line) // 45) + 1
496
- calculated_height = lines * 24 + 30
497
- ws.row_dimensions[row].height = max(min_height, calculated_height)
498
-
499
- return row + 1
500
-
501
-
502
- def generate_excel(data):
503
- wb = Workbook()
504
- title_fill = PatternFill("solid", fgColor="FFEDD5")
505
- header_fill = PatternFill("solid", fgColor="F3F4F6")
506
-
507
- ws = wb.active
508
- ws.title = "급여제공지침교육일지"
509
-
510
- ws.page_setup.paperSize = ws.PAPERSIZE_A4
511
- ws.page_setup.orientation = "portrait"
512
- ws.page_setup.fitToWidth = 1
513
- ws.page_setup.fitToHeight = 0 # 0으로 설정하여 여러 페이지 출력을 허용합니다.
514
- ws.sheet_properties.pageSetUpPr.fitToPage = True
515
- ws.page_margins.left = 0.3
516
- ws.page_margins.right = 0.3
517
- ws.page_margins.top = 0.4
518
- ws.page_margins.bottom = 0.4
519
- ws.sheet_view.showGridLines = False
520
-
521
- # 제목에서 Beecare 제외, 우측 상단 결재라인
522
- write_title_with_approval(ws, "급여제공지침 교육일지", title_fill, header_fill)
523
-
524
- r = 3
525
- write_info_row(ws, r, "기관명", data["institution_name"], "기관유형", data["institution_type"], "교육일자", data["education_date"], header_fill); r += 1
526
- write_info_row(ws, r, "교육명", data["education_title"], "교육시간", data["education_time"], "교육장소", data["education_place"], header_fill); r += 1
527
- write_info_row(ws, r, "강사명", data["instructor_name"], "강사직책", data["instructor_position"], "교육방법", data["education_method"], header_fill); r += 1
528
-
529
- r = write_section(ws, r, "교육지침", data["guideline_items"], header_fill, 80)
530
-
531
- # ==== 참석자 명단 (직종별 분할 레이아웃) ====
532
- ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=9)
533
- ws.cell(r, 1).value = "참석자 명단"
534
- ws.cell(r, 1).font = Font(name="Malgun Gothic", size=15, bold=True)
535
- ws.cell(r, 1).alignment = Alignment(horizontal="center", vertical="center")
536
- ws.cell(r, 1).fill = header_fill
537
- style_range(ws, f"A{r}:I{r}")
538
- ws.row_dimensions[r].height = 30
539
- r += 1
540
-
541
- att = data.get("attendees_dict", {})
542
- write_attendee_row(ws, r, "시설장", att.get("시설장", ""), "사회복지사", att.get("사회복지사", ""), "물리치료사", att.get("물리치료사", ""), header_fill); r += 1
543
- write_attendee_row(ws, r, "간호조무사", att.get("간호조무사", ""), "요양보호사", att.get("요양보호사", ""), "기타직종", att.get("기타", ""), header_fill); r += 1
544
-
545
- # =========================================
546
-
547
- r = write_section(ws, r, "미참석자 및 보충교육 계획", data["absent_staff"] or "미참석자 없음", header_fill, 70)
548
- r = write_section(ws, r, "교육목적", data["education_purpose"], header_fill, 110)
549
- r = write_section(ws, r, "교육내용", data["education_content"], header_fill, 260)
550
- r = write_section(ws, r, "교육자료 첨부/자료명", data["education_materials"], header_fill, 80)
551
-
552
- # ==== 여기서 1페이지 끊기 (가로 페이지 구분선 삽입) ====
553
- ws.row_breaks.append(Break(id=r-1))
554
-
555
- # ==== 2페이지: 교육결�� 및 이미지 ====
556
- r = write_section(ws, r, "교육결과", data["education_result"], header_fill, 150)
557
-
558
- # 자체점검용 '후속조치'와 '평가적합도'는 엑셀에 출력하지 않도록 삭제하였습니다.
559
-
560
- # 교육자료 이미지 첨부: 이미지 파일일 때만 삽입
561
- image_paths = [p for p in data.get("material_paths", []) if os.path.splitext(p)[1].lower() in [".png", ".jpg", ".jpeg"]]
562
- if image_paths:
563
- ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=9)
564
- ws.cell(r, 1).value = "교육자료 이미지"
565
- ws.cell(r, 1).font = Font(name="Malgun Gothic", size=15, bold=True)
566
- ws.cell(r, 1).alignment = Alignment(horizontal="center", vertical="center")
567
- ws.cell(r, 1).fill = header_fill
568
- style_range(ws, f"A{r}:I{r}")
569
- r += 1
570
-
571
- anchors = ["A", "D", "G"]
572
- img_row = r
573
- for idx, img_path in enumerate(image_paths[:3]):
574
- try:
575
- img = XLImage(img_path)
576
- img.width = 210
577
- img.height = 150
578
- ws.add_image(img, f"{anchors[idx]}{img_row}")
579
- except Exception:
580
- pass
581
-
582
- # 이미지 영역 병합 및 스타일 적용
583
- ws.merge_cells(start_row=img_row, start_column=1, end_row=img_row+7, end_column=9)
584
- style_range(ws, f"A{img_row}:I{img_row+7}")
585
- for rr in range(img_row, img_row + 8):
586
- ws.row_dimensions[rr].height = 22
587
- r = img_row + 8
588
-
589
- output = BytesIO()
590
- wb.save(output)
591
- output.seek(0)
592
- return output
593
-
594
-
595
- # -----------------------------
596
- # 화면
597
- # -----------------------------
598
- menu = st.sidebar.radio("메뉴", ["교육일지 생성", "교육기록 보기"])
599
-
600
- st.sidebar.success("DB 연결")
601
- st.sidebar.caption(DB_PATH)
602
-
603
- if menu == "교육기록 보기":
604
- st.subheader("📚 저장된 교육기록")
605
- records = load_education_records()
606
- if records.empty:
607
- st.info("저장된 교육기록이 없습니다.")
608
- else:
609
- st.dataframe(records, use_container_width=True)
610
-
611
- elif menu == "교육일지 생성":
612
- st.subheader("📘 급여제공지침 교육일지 생성")
613
-
614
- col1, col2, col3 = st.columns(3)
615
- # 초기 기관명에서 Beecare 삭제
616
- institution_name = col1.text_input("기관명", "장기요양기관")
617
- institution_type = col2.selectbox("기관유형", ["방문요양", "방문목욕", "방문간호", "주간보호", "요양원", "공동생활가정"])
618
- education_title = col3.text_input("교육명", "급여제공지침 종사자 교육")
619
-
620
- col4, col5, col6 = st.columns(3)
621
- education_date = col4.date_input("교육일자", value=date.today())
622
- education_time = col5.text_input("교육시간", "14:00~15:00")
623
- education_place = col6.text_input("교육장소", "기관 내 프로그램실")
624
-
625
- col7, col8, col9 = st.columns(3)
626
- instructor_name = col7.text_input("강사명", "시설장")
627
- instructor_position = col8.text_input("강사직책", "시설장")
628
- education_method = col9.selectbox("교육방법", METHODS)
629
-
630
- selected_guidelines = st.multiselect(
631
- "교육 지침 선택",
632
- list(GUIDELINES.keys()),
633
- default=["02. 노인인권보호지침", "03. 노인학대예방지침", "07. 감염예방 및 관리지침", "09. 낙상예방지침"]
634
- )
635
-
636
- st.markdown("### 직종별 참석자 명단 입력")
637
- st.caption("각 칸에 참석자의 이름을 직접 쉼표나 띄어쓰기로 구분하여 입력해주세요.")
638
-
639
- a1, a2, a3 = st.columns(3)
640
- att_director = a1.text_input("시설장", placeholder="예: 홍길동")
641
- att_social = a2.text_input("사회복지사", placeholder="예: 김복지")
642
- att_therapist = a3.text_input("물리치료사", placeholder="예: 이치료")
643
-
644
- a4, a5, a6 = st.columns(3)
645
- att_nurse = a4.text_input("간호조무사", placeholder="예: 박간호")
646
- att_caregiver = a5.text_input("요양보호사", placeholder="예: 최요양, 정요양")
647
- att_others = a6.text_input("기타 직종", placeholder="예: 조리원 김조리")
648
-
649
- # 입력된 데이터를 딕셔너리와 문자열로 변환
650
- attendees_dict = {
651
- "시설장": att_director,
652
- "사회복지사": att_social,
653
- "물리치료사": att_therapist,
654
- "간호조무사": att_nurse,
655
- "요양보호사": att_caregiver,
656
- "기타": att_others
657
- }
658
- attendees_summary = "\n".join([f"[{k}] {v}" for k, v in attendees_dict.items() if v.strip()])
659
-
660
- absent_staff = st.text_area(
661
- "미참석자 및 보충교육 계획",
662
- placeholder="예: 박요양보호사 연차로 미참석, 6월 20일 개별 보충교육 예정",
663
- height=80
664
- )
665
-
666
- custom_content = st.text_area(
667
- "기관 추가 교육내용",
668
- placeholder="기관에서 실제 발생할 수 있는 사례, 자체 운영규정, 유의사항 등을 입력하세요.",
669
- height=90
670
- )
671
-
672
- education_material_files = st.file_uploader(
673
- "교육자료 첨부 (이미지/PDF/문서 가능, 최대 3개)",
674
- type=["png", "jpg", "jpeg", "pdf", "docx", "xlsx"],
675
- accept_multiple_files=True
676
- )
677
-
678
- material_paths, material_names = save_uploaded_materials(education_material_files)
679
- material_text = ", ".join(material_names) if material_names else "급여제공지침 교육자료 비치 및 공개게시 자료 사용"
680
-
681
- purpose, content = build_education_text(
682
- selected_guidelines,
683
- institution_type,
684
- education_method,
685
- custom_content
686
- )
687
-
688
- result_text = build_result_text(
689
- selected_guidelines,
690
- attendees_dict,
691
- absent_staff,
692
- education_method
693
- ) if selected_guidelines else ""
694
-
695
- followup_plan = st.text_area(
696
- "후속조치 및 현장 적용계획",
697
- value="급여제공지침 교육자료를 기관 내 종사자가 확인하기 쉬운 장소에 공개 게시하고, 종사자가 수시로 지침 내용을 확인하여 실제 급여제공에 반영하도록 한다. 교육 후 종사자가 현장에서 지침을 준수하는지 모니터링하고, 미참석자 또는 신규직원에 대해서는 보충교육을 실시한다.",
698
- height=100
699
- )
700
-
701
- if st.button("📘 교육일지 생성", use_container_width=True):
702
- data = {
703
- "institution_name": institution_name,
704
- "institution_type": institution_type,
705
- "education_title": education_title,
706
- "guideline_items": "\n".join(selected_guidelines),
707
- "education_date": str(education_date),
708
- "education_time": education_time,
709
- "education_place": education_place,
710
- "instructor_name": instructor_name,
711
- "instructor_position": instructor_position,
712
- "attendees_dict": attendees_dict,
713
- "attendees": attendees_summary, # 평가 로직 및 DB 저장용
714
- "absent_staff": absent_staff,
715
- "education_method": education_method,
716
- "education_purpose": purpose,
717
- "education_content": content,
718
- "education_materials": material_text,
719
- "education_result": result_text,
720
- "followup_plan": followup_plan,
721
- "material_paths": material_paths,
722
- }
723
-
724
- score, missing, compliance = evaluate_education(data)
725
- data["evaluation_score"] = score
726
- data["missing_items"] = ", ".join(missing) if missing else "부족 항목 없음"
727
- data["compliance_result"] = compliance
728
-
729
- st.session_state["edu_data"] = data
730
-
731
- if "edu_data" in st.session_state:
732
- data = st.session_state["edu_data"]
733
-
734
- st.markdown("---")
735
- st.subheader("생성 결과 수정")
736
-
737
- data["education_purpose"] = st.text_area("교육목적", value=data["education_purpose"], height=140)
738
- data["education_content"] = st.text_area("교육내용", value=data["education_content"], height=260)
739
- data["education_result"] = st.text_area("교육결과", value=data["education_result"], height=140)
740
-
741
- # UI/DB용으로는 유지
742
- data["followup_plan"] = st.text_area("후속조치 (엑셀 출력 제외)", value=data["followup_plan"], height=100)
743
-
744
- score, missing, compliance = evaluate_education(data)
745
- data["evaluation_score"] = score
746
- data["missing_items"] = ", ".join(missing) if missing else "부족 항목 없음"
747
- data["compliance_result"] = compliance
748
-
749
- st.subheader("평가 적합도 점검 (자체 보관용 / 엑셀 출력 제외)")
750
- e1, e2, e3 = st.columns(3)
751
- e1.metric("평가 적합도", f"{score}점")
752
- e2.metric("부족 항목", data["missing_items"])
753
- e3.metric("결재라인", "담당자/시설장 2칸")
754
-
755
- if score >= 90:
756
- st.markdown(f'<div class="okbox">{compliance}</div>', unsafe_allow_html=True)
757
- else:
758
- st.markdown(f'<div class="warnbox">{compliance}</div>', unsafe_allow_html=True)
759
-
760
- if st.button("💾 교육기록 DB 저장", use_container_width=True):
761
- save_education_record(data)
762
- st.success("교육기록이 저장되었습니다.")
763
-
764
- filename = f"급여제공지침교육일지_{data['education_date']}.xlsx"
765
- st.download_button(
766
- "📥 급여제공지침 교육일지 엑셀 다운로드",
767
- data=generate_excel(data),
768
- file_name=filename,
769
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
770
- use_container_width=True,
771
- )
772
-
773
- # 하단 캡션 수정
774
- st.caption("급여제공지침 교육일지 생성기")