FluxFinance commited on
Commit
83ae777
·
verified ·
1 Parent(s): e54d9bb

Upload Advisernote.py

Browse files
Files changed (1) hide show
  1. Advisernote.py +1405 -0
Advisernote.py ADDED
@@ -0,0 +1,1405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import io
4
+ import os
5
+ import json
6
+ import sys
7
+ import warnings
8
+ import platform
9
+ import imaplib
10
+ import email
11
+ from imaplib import IMAP4_SSL
12
+ from email.header import decode_header, make_header
13
+ from datetime import datetime
14
+ from docx import Document
15
+ from docx.shared import Pt, RGBColor, Inches
16
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
17
+ from docx.oxml.ns import qn
18
+ from docx.oxml import OxmlElement
19
+ import pdfplumber
20
+ import vertexai
21
+ import toml
22
+ import requests
23
+ import copy
24
+ import re
25
+ import sqlite3
26
+
27
+ # 1. 인증 및 Secrets 통합 로드
28
+ creds_json_str = st.secrets.get("GCP_CREDENTIALS")
29
+ if creds_json_str:
30
+ with open("credentials.json", "w") as f:
31
+ f.write(creds_json_str)
32
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "credentials.json"
33
+
34
+ # 2. 모든 필수 변수 한 번에 선언 (변수명 일치 확인)
35
+ COMMON_PW = st.secrets["EMAIL_PASSWORD"]
36
+ MASTER_PW = st.secrets["MASTER_PASSWORD"]
37
+ ADMIN_EMAIL = st.secrets["ADMIN_EMAIL"]
38
+ PROJECT_ID = st.secrets["PROJECT_ID"]
39
+ NOTION_TOKEN = st.secrets["NOTION_API_TOKEN"]
40
+ NOTION_DB_ID = st.secrets["NOTION_DATABASE_ID"]
41
+
42
+ # 3. 리스트/딕셔너리 변환 로직
43
+ ALL_MAILBOXES = st.secrets["ALL_MAILBOXES"].split(",")
44
+ users_str = st.secrets["ALLOWED_USERS"]
45
+ allowed_users = {item.split("=")[0].strip(): item.split("=")[1].strip() for item in users_str.split(",") if "=" in item}
46
+
47
+ def save_rules_to_db(df):
48
+ conn = sqlite3.connect("data.db")
49
+ df.to_sql("compliance_rules", conn, if_exists="replace", index=False)
50
+ conn.close()
51
+
52
+ def load_rules_from_db():
53
+ conn = sqlite3.connect("data.db")
54
+ try:
55
+ df = pd.read_sql("SELECT * FROM compliance_rules", conn)
56
+ except:
57
+ df = pd.DataFrame()
58
+ conn.close()
59
+ return df
60
+
61
+ # [1] System Settings & OS Detection
62
+ OS_TYPE = platform.system()
63
+ warnings.filterwarnings("ignore")
64
+
65
+ if OS_TYPE == "Windows":
66
+ try:
67
+ import win32com.client
68
+ except ImportError:
69
+ pass
70
+
71
+ st.set_page_config(page_title="Flux Finance Internal Note", layout="wide")
72
+
73
+ # 🎨 UI Style
74
+ st.markdown("""
75
+ <style>
76
+ .stApp { background-color: #F8FAFC; }
77
+ /* 사이드바 너비를 늘려 메인 영역과 50:50 비율에 가깝게 설정 */
78
+ section[data-testid="stSidebar"] {
79
+ order: 2;
80
+ width: 50% !important; /* 비율을 50%로 설정 */
81
+ min-width: 700px !important; /* 최소 너비 증가 */
82
+ max-width: 50% !important; /* 최대 너비도 50%로 제한 */
83
+ background-color: #FFFFFF;
84
+ border-left: 2px solid #E2E8F0;
85
+ }
86
+ div.stButton > button { width: 100% !important; background-color: #1E3A8A !important; color: white !important; font-weight: 700; padding: 0.8rem; }
87
+ .status-container { background-color: #F1F5F9; padding: 15px; border-radius: 10px; margin-bottom: 20px; border: 1px solid #E2E8F0; }
88
+ .status-item { font-size: 0.82rem; margin-bottom: 5px; display: flex; align-items: center; }
89
+ .dot { height: 10px; width: 10px; border-radius: 50%; display: inline-block; margin-right: 8px; }
90
+ .dot-filled { background-color: #10B981; box-shadow: 0 0 8px #10B981; }
91
+ .dot-orange { background-color: #F59E0B; box-shadow: 0 0 8px #F59E0B; }
92
+ .dot-empty { background-color: #CBD5E1; }
93
+ .unified-guide { background-color: #EFF6FF; color: #1E40AF; padding: 12px 18px; border-radius: 8px; border-left: 5px solid #3B82F6; margin-bottom: 20px; font-size: 0.85rem; }
94
+ .mail-info { font-size: 0.85rem; color: #475569; margin-bottom: 8px; border-bottom: 1px dashed #CBD5E1; }
95
+ .content-box { background-color: #F9FAFB; padding: 15px; border-radius: 8px; border: 1px solid #E5E7EB; font-size: 0.88rem; max-height: 400px; overflow-y: auto; white-space: pre-wrap; line-height: 1.6; }
96
+ .attach-box { font-size: 0.78rem; color: #059669; background-color: #F0FDF4; padding: 6px 10px; border-radius: 6px; border: 1px solid #BBF7D0; margin-top: 10px; }
97
+ .type-tag { font-size: 0.7rem; font-weight: 800; padding: 2px 6px; border-radius: 4px; margin-right: 8px; }
98
+ .sent { background-color: #DBEAFE; color: #1E40AF; }
99
+ .received { background-color: #FEF3C7; color: #92400E; }
100
+ </style>
101
+ """, unsafe_allow_html=True)
102
+
103
+ # Session State Initialization
104
+ if 'drafts' not in st.session_state: st.session_state['drafts'] = {}
105
+ if 'emails' not in st.session_state: st.session_state['emails'] = ""
106
+ if 'client_names' not in st.session_state: st.session_state['client_names'] = ""
107
+ if 'support_name' not in st.session_state: st.session_state['support_name'] = ""
108
+ if 'refs' not in st.session_state: st.session_state['refs'] = ""
109
+ if 'folder_path' not in st.session_state: st.session_state['folder_path'] = ""
110
+ if 'doc_context' not in st.session_state: st.session_state['doc_context'] = ""
111
+ if 'results' not in st.session_state: st.session_state['results'] = None
112
+ if 'notion_client_name' not in st.session_state: st.session_state['notion_client_name'] = "Serafi & Tusiga"
113
+
114
+ # =========================================================================
115
+ # [보안 끝판왕] 최초 로그인 비번 세팅 & 관리자 실시간 동기화/삭제 통제 시스템
116
+ # =========================================================================
117
+ def save_secrets_to_file(secrets_dict):
118
+ """실시간으로 변경된 비밀번호와 직원 명단을 TOML 파일(Secrets)에 영구 기록하는 함수"""
119
+ try:
120
+ secrets_path = ".streamlit/secrets.toml"
121
+ with open(secrets_path, "w", encoding="utf-8") as f:
122
+ toml.dump(secrets_dict, f)
123
+ return True
124
+ except:
125
+ return False
126
+
127
+ def check_password():
128
+ """로그인 검증, 최초 접속자 비번 세팅, 관리자 전용 대시보드 스위칭 마스터 함수"""
129
+ if "password_correct" not in st.session_state:
130
+ st.session_state["password_correct"] = False
131
+ if "is_admin_mode" not in st.session_state:
132
+ st.session_state["is_admin_mode"] = False
133
+
134
+ if st.session_state["password_correct"]:
135
+ return True
136
+
137
+ # 🎨 [디자인 혁신] 3열 분할 레이아웃을 사용해 로그인 창을 화면 정중앙에 예쁜 카드로 배치
138
+ _, login_col, _ = st.columns([1, 1.1, 1])
139
+
140
+ with login_col:
141
+ st.write("") # 상단 여백 세팅
142
+ st.write("")
143
+ with st.container(border=True):
144
+ st.markdown("""
145
+ <div style='text-align: center; margin-bottom: 25px;'>
146
+ <span style='font-size: 2.3rem;'>🔒</span>
147
+ <h2 style='color: #1E3A8A; margin: 10px 0 4px 0; font-size: 1.45rem; font-weight: 800; letter-spacing: -0.5px;'>Flux Finance</h2>
148
+ <p style='color: #64748B; font-size: 0.82rem; margin: 0;'>Internal System Access Portal</p>
149
+ </div>
150
+ """, unsafe_allow_html=True)
151
+
152
+ allowed_users = dict(st.secrets.get("ALLOWED_USERS", {}))
153
+ admin_info = st.secrets.get("ADMIN_CONFIG", {})
154
+
155
+ input_email = st.text_input("📧 Login Email Address", key="login_email", placeholder="username@fluxfinance.co.nz").strip().lower()
156
+
157
+ if input_email and (input_email != admin_info.get("EMAIL") and input_email not in allowed_users):
158
+ st.error("❌ Access Denied: This account is unregistered or has been deactivated. Please contact the administrator.")
159
+ return False
160
+
161
+ # Case A: 최고 관리자(매니저님) 접속 시 (기능 100% 동일)
162
+ if input_email == admin_info.get("EMAIL"):
163
+ input_password = st.text_input("👑 Admin Password", type="password", key="login_password", placeholder="Enter admin password")
164
+ if st.button("Sign In as Manager", use_container_width=True):
165
+ if input_password == admin_info.get("PASSWORD"):
166
+ st.session_state["password_correct"] = True
167
+ st.session_state["is_admin_mode"] = True
168
+ st.rerun()
169
+ else:
170
+ st.error("❌ Incorrect Administrator password.")
171
+ return False
172
+
173
+ # Case B: 일반 직원 접속 시 (기능 100% 동일)
174
+ if input_email in allowed_users: # 위에서 만든 딕셔너리 사용
175
+ current_db_pwd = allowed_users[input_email]
176
+
177
+ # 상황 ①: 최초 접속이라 비번이 비어있을 때 ("") -> 초기 셋업 로직 완벽 보존
178
+ if current_db_pwd == "":
179
+ st.warning("🆕 Welcome! Please set up your personalized password for this account.")
180
+ new_pwd = st.text_input("🔑 Create New Password", type="password", key="setup_pwd")
181
+ confirm_pwd = st.text_input("🔄 Confirm New Password", type="password", key="confirm_pwd")
182
+
183
+ if st.button("Activate My Account", use_container_width=True):
184
+ if new_pwd and new_pwd == confirm_pwd:
185
+ all_secrets = {k: (dict(v) if hasattr(v, "items") else v) for k, v in st.secrets.items()}
186
+ all_secrets["ALLOWED_USERS"][input_email] = new_pwd
187
+ if save_secrets_to_file(all_secrets):
188
+ st.success("✅ Password configured successfully! Please sign in again with your new password.")
189
+ st.rerun()
190
+ else:
191
+ st.error("⚠️ System Error: Failed to write system files. Please verify file permissions.")
192
+ else:
193
+ st.error("❌ Passwords do not match or fields are left blank.")
194
+ return False
195
+
196
+ # 상황 ②: 이미 비번 세팅이 끝나서 정상 로그인을 시도할 때 -> 로그인 로직 완벽 보존
197
+ else:
198
+ input_password = st.text_input("🔑 Password", type="password", key="login_password", placeholder="Enter your system password")
199
+ col_login, col_change = st.columns([1, 1])
200
+
201
+ with col_login:
202
+ if st.button("Sign In", use_container_width=True):
203
+ if input_password == current_db_pwd:
204
+ st.session_state["password_correct"] = True
205
+ st.session_state["is_admin_mode"] = False
206
+ st.rerun()
207
+ else:
208
+ st.error("❌ Invalid password. Please try again.")
209
+
210
+ # 상황 ③: 직원이 마이페이지에서 비밀번호 변경을 요청할 때 -> 토스트 팝업 로직 완벽 보존
211
+ with col_change:
212
+ with st.popover("🔄 Change Password", use_container_width=True):
213
+ st.write("Verify your current password to update your credentials.")
214
+ verify_old = st.text_input("Current Password", type="password", key="v_old")
215
+ update_new = st.text_input("New Password", type="password", key="u_new")
216
+
217
+ if st.button("Update Password", use_container_width=True):
218
+ if verify_old == current_db_pwd and update_new:
219
+ all_secrets = dict(st.secrets)
220
+ all_secrets["ALLOWED_USERS"][input_email] = update_new
221
+ if save_secrets_to_file(all_secrets):
222
+ st.toast("✅ Password updated successfully!", icon="🚀")
223
+ st.rerun()
224
+ else:
225
+ st.error("❌ Current password verification failed or input is missing.")
226
+ return False
227
+ # =========================================================================
228
+ # [NOTION API CONNECTOR] 노션 페이지 본문 및 모든 실시간 댓글 병합 수집기
229
+ # =========================================================================
230
+ # =========================
231
+ # 1. 댓글 가져오기
232
+ # =========================
233
+ def fetch_notion_comments(page_id):
234
+ """노션 특정 페이지의 댓글과 작성 날짜를 함께 추출하는 함수"""
235
+ notion_token = st.secrets.get("NOTION_API_TOKEN", "")
236
+ headers = {
237
+ "Authorization": f"Bearer {notion_token}",
238
+ "Notion-Version": "2025-09-03"
239
+ }
240
+ try:
241
+ url = f"https://api.notion.com/v1/comments?block_id={page_id}"
242
+ response = requests.get(url, headers=headers)
243
+ if response.status_code == 200:
244
+ comments_data = response.json().get("results", [])
245
+ comments_list = []
246
+ for c in comments_data:
247
+ # 🟢 [수정] 작성 날짜(created_time)를 가져옵니다.
248
+ created_at = c.get("created_time", "").split("T")[0] # YYYY-MM-DD 형식만 추출
249
+
250
+ c_text_list = c.get("rich_text", [])
251
+ c_text = c_text_list[0].get("text", {}).get("content", "").strip() if c_text_list else ""
252
+
253
+ if c_text:
254
+ # 🟢 [수정] [날짜] 코멘트 내용 형식으로 조합
255
+ comments_list.append(f"💬 [{created_at}] {c_text}")
256
+ return "\n".join(comments_list) if comments_list else ""
257
+ except:
258
+ pass
259
+ return ""
260
+
261
+ def fetch_client_tasks_from_notion(client_name):
262
+ # .streamlit/secrets.toml 파일에서 보안 정보를 안전하게 로드합니다.
263
+ notion_token = st.secrets.get("NOTION_API_TOKEN", "")
264
+ target_data_source_id = st.secrets.get("NOTION_DATABASE_ID", "")
265
+
266
+ if not notion_token:
267
+ return [], "Missing NOTION_API_TOKEN in secrets.toml"
268
+ if not target_data_source_id:
269
+ return [], "Missing NOTION_DATABASE_ID in secrets.toml"
270
+
271
+ headers = {
272
+ "Authorization": f"Bearer {notion_token.strip()}",
273
+ "Content-Type": "application/json",
274
+ "Notion-Version": "2025-09-03"
275
+ }
276
+
277
+ # 윈도우 시스템 주소 오타 변조 및 가로채기 차단용 우회 함수
278
+ def get_clean_url(endpoint_path):
279
+ p1 = "ht" + "tps://"
280
+ p2 = "ap" + "i.no" + "tion.c" + "om/"
281
+ return p1 + p2 + endpoint_path
282
+
283
+ # secrets.toml에서 가져온 진짜 데이터 소스 ID 기반의 쿼리 주소 생성
284
+ query_url = get_clean_url(f"v1/data_sources/{target_data_source_id.strip()}/query/")
285
+
286
+ # 입력한 고객 이름과 정확히 일치하는 행만 타겟팅하는 필터 딜리버리
287
+ payload = {
288
+ "filter": {
289
+ "property": "Case Name",
290
+ "rich_text": {
291
+ "equals": client_name.strip()
292
+ }
293
+ }
294
+ }
295
+
296
+ clean_proxies = {"http": None, "https": None}
297
+
298
+ # 1. 원본 데이터 소스 조회
299
+ response = requests.post(query_url, json=payload, headers=headers, proxies=clean_proxies)
300
+ if response.status_code != 200:
301
+ return [], f"Notion API Failed: {response.status_code}"
302
+
303
+ results = response.json().get("results", [])
304
+ if not results:
305
+ return [], f"No case found named '{client_name}'."
306
+
307
+ # 2. 검색 정합성이 검증된 실시간 데이터 행에서 하위 Task ID 추출
308
+ target_case = results[0]
309
+ case_id = target_case.get("id")
310
+
311
+ # 🟢 [수정 1] 부모 케이스(Case) 페이지에 있는 전체 코멘트 추출
312
+ case_comments = fetch_notion_comments(case_id)
313
+
314
+ task_ids = []
315
+ for prop in target_case.get("properties", {}).values():
316
+ if prop.get("type") == "relation":
317
+ for r in prop.get("relation", []):
318
+ task_ids.append(r.get("id"))
319
+
320
+ tasks_list = []
321
+
322
+ # 3. 각 하위 개별 Task 상세 필드 파싱
323
+ for tid in task_ids:
324
+ page_url = get_clean_url(f"v1/pages/{tid}")
325
+ page_res = requests.get(page_url, headers=headers, proxies=clean_proxies)
326
+
327
+ if page_res.status_code == 200:
328
+ page_data = page_res.json()
329
+ props = page_data.get("properties", {})
330
+
331
+ title = "제목 없음"
332
+ description = "내용 없음"
333
+ date_val = datetime.now().strftime("%Y-%m-%d")
334
+ channel_val = "-"
335
+
336
+ for key, v in props.items():
337
+ normalized_key = key.strip().lower()
338
+ p_type = v.get("type")
339
+
340
+ if p_type == "title":
341
+ t_list = v.get("title", [])
342
+ if isinstance(t_list, list) and len(t_list) > 0:
343
+ parts = [item.get("plain_text", "") for item in t_list if isinstance(item, dict)]
344
+ if parts: title = "".join(parts)
345
+
346
+ elif "completed" in normalized_key:
347
+ if p_type == "date" and v.get("date"):
348
+ date_val = v["date"].get("start", date_val)
349
+ elif p_type == "rich_text":
350
+ r_list = v.get("rich_text", [])
351
+ if isinstance(r_list, list) and len(r_list) > 0:
352
+ parts = [item.get("plain_text", "") for item in r_list if isinstance(item, dict)]
353
+ if parts: date_val = "".join(parts)
354
+
355
+ elif "description" in normalized_key:
356
+ if p_type == "rich_text":
357
+ r_list = v.get("rich_text", [])
358
+ if isinstance(r_list, list) and len(r_list) > 0:
359
+ parts = [item.get("plain_text", "") for item in r_list if isinstance(item, dict)]
360
+ if parts: description = "".join(parts)
361
+
362
+ elif "channel" in normalized_key:
363
+ if p_type == "select" and v.get("select"):
364
+ channel_val = v["select"].get("name", "-")
365
+ elif p_type == "multi_select" and v.get("multi_select"):
366
+ channel_val = ", ".join([m.get("name", "") for m in v["multi_select"]])
367
+ elif p_type == "rich_text":
368
+ r_list = v.get("rich_text", [])
369
+ if isinstance(r_list, list) and len(r_list) > 0:
370
+ parts = [item.get("plain_text", "") for item in r_list if isinstance(item, dict)]
371
+ if parts: channel_val = "".join(parts)
372
+
373
+ comments_text = fetch_notion_comments(tid)
374
+
375
+ tasks_list.append({
376
+ "Date": date_val,
377
+ "Body": description,
378
+ "Sec": title,
379
+ "RawTitle": title,
380
+ "Type": "NOTION",
381
+ "Channel": channel_val,
382
+ "Comments": comments_text
383
+ })
384
+
385
+ # 4. 태스크 번호 오름차순 정렬
386
+ if tasks_list:
387
+ tasks_list = sorted(tasks_list, key=lambda x: x["Sec"])
388
+
389
+ # 🟢 튜플 리턴값 3개로 확장 (case_comments 포함)
390
+ return tasks_list, "Success", case_comments
391
+
392
+ if check_password():
393
+ # Render HR & Security Control Panel if Manager logs in
394
+
395
+ RULES_FILE = "compliance_rules.json"
396
+
397
+ if 'rules_df' not in st.session_state:
398
+ if os.path.exists(RULES_FILE):
399
+ try: st.session_state['rules_df'] = pd.read_json(RULES_FILE, encoding='utf-8')
400
+ except: pass
401
+ # 파일이 없으면 오리지널 10대 기본 구조 생성
402
+ if 'rules_df' not in st.session_state:
403
+ data = [
404
+ {"No": "1", "Stage Title": "INITIAL MEETING", "Sub 1": "Initial Meeting", "Sub 2": "", "Keywords": "", "Action": "Conducted a face-to-face discovery meeting to verify original ID and discuss client objectives.", "Purpose": "To satisfy AML/CFT requirements via face-to-face ID verification and gather financial data for lending strategy."},
405
+ {"No": "2", "Stage Title": "DISCLOSURE DELIVERY", "Sub 1": "Disclosure Delivery", "Sub 2": "", "Keywords": "Disclosure, D1, D2", "Action": "Emailed full FAP Disclosure or provided public info.", "Purpose": "To ensure clients review scope of service and licensing."},
406
+ {"No": "3", "Stage Title": "DOCUMENT COLLECTION", "Sub 1": "Required documents requested", "Sub 2": "Required documents received", "Keywords": "Attachment: Payslip, Statement, ID", "Action": "Verified core docs or requested further clarification.", "Purpose": "To assess borrowing capacity and meet lender standards."},
407
+ {"No": "4", "Stage Title": "STRATEGY & ADVICE", "Sub 1": "Strategy & Advice", "Sub 2": "", "Keywords": "Fact Find, Scope of Work, SOW", "Action": "Discussed bank-specific policies and compared products.", "Purpose": "To align the application with the best possible lender/rate."},
408
+ {"No": "5", "Stage Title": "APPLICATION SUBMISSION", "Sub 1": "Application Submission", "Sub 2": "", "Keywords": "", "Action": "Reviewed SOW/Fact-Find and formally lodged application.", "Purpose": "To ensure data accuracy before formal credit assessment."},
409
+ {"No": "6", "Stage Title": "LENDER QUERY", "Sub 1": "Bank Query Received", "Sub 2": "Query Response Sent", "Keywords": "", "Action": "Received and addressed technical queries from the lender.", "Purpose": "To satisfy credit requirements and progress the file."},
410
+ {"No": "7", "Stage Title": "CONDITIONAL APPROVAL", "Sub 1": "Conditional approval received", "Sub 2": "Conditional approval provided to client", "Keywords": "Letter of Offer, LOO", "Action": "Reviewed conditional approval and updated the clients.", "Purpose": "To identify and guide clients through remaining conditions."},
411
+ {"No": "8", "Stage Title": "LOAN STRUCTURE REVIEW", "Sub 1": "Proposed Structure Discussed", "Sub 2": "Final Instruction to Lender", "Keywords": "Statement of Advice, SOA", "Action": "Provided SOA and confirmed final interest rate lock-in.", "Purpose": "To ensure the loan structure meets the client's risk profile."},
412
+ {"No": "9", "Stage Title": "FINAL APPROVAL", "Sub 1": "Final Approval", "Sub 2": "", "Keywords": "Final, Unconditional", "Action": "Received final approval and instructed the solicitor.", "Purpose": "To confirm all conditions met and initiate legal process."},
413
+ {"No": "10", "Stage Title": "SETTLEMENT COMPLETION", "Sub 1": "Settlement Completion", "Sub 2": "", "Keywords": "Settlement", "Action": "Coordinated funds and confirmed successful completion.", "Purpose": "To finalize the advice process and transition to service."}
414
+ ]
415
+ st.session_state['rules_df'] = pd.DataFrame(data)
416
+
417
+ # 1️⃣ [최상단] Admin 전용 통제 구역 (Manager 로그인 시에만 노출)
418
+ if st.session_state.get("is_admin_mode", False):
419
+ with st.expander("👑 Admin Control", expanded=False):
420
+ st.markdown("### 👑 Admin Control")
421
+ st.caption("Monitor real-time password setups for active team members and revoke access for offboarded employees.")
422
+
423
+ # [🔥 FIXED] Deep copy all nested layers to allow dictionary item deletion without Streamlit restrictions
424
+ import copy
425
+ raw_secrets = {k: (dict(v) if hasattr(v, "items") else v) for k, v in st.secrets.items()}
426
+ all_secrets = copy.deepcopy(raw_secrets)
427
+
428
+ current_users = all_secrets.get("ALLOWED_USERS", {})
429
+ admin_data = []
430
+
431
+ for u_email, u_pwd in current_users.items():
432
+ status_tag = "🔴 Pending Setup" if u_pwd == "" else "🟢 Active (Password Set)"
433
+
434
+ # [🔒 SECURITY MASKING] Convert plain text passwords (e.g., "dong9ri1" -> "d*******")
435
+ if u_pwd and len(u_pwd) > 1:
436
+ masked_pwd = u_pwd[0] + "*" * (len(u_pwd) - 1)
437
+ elif u_pwd:
438
+ masked_pwd = "*"
439
+ else:
440
+ masked_pwd = "(None)"
441
+
442
+ admin_data.append({
443
+ "Employee Email": u_email,
444
+ "Recorded Password": masked_pwd, # Displays secure masked version on screen
445
+ "Status": status_tag
446
+ })
447
+
448
+ st.table(pd.DataFrame(admin_data))
449
+
450
+ st.markdown("**Deactivate & Revoke User Permissions**")
451
+ target_del = st.selectbox("Select email address to revoke access", ["-"] + list(current_users.keys()))
452
+
453
+ if target_del != "-" and st.button("🚨 Revoke Access"):
454
+ if target_del in all_secrets["ALLOWED_USERS"]:
455
+ # Successfully deletes the user without throwing __delitem__ error
456
+ del all_secrets["ALLOWED_USERS"][target_del]
457
+ if save_secrets_to_file(all_secrets):
458
+ st.success(f"⚠️ Access permanently revoked for {target_del}. This user can no longer sign in.")
459
+ st.rerun()
460
+
461
+ # (2) 규칙 편집 관리 (Rules Configuration - Admin Control 바로 밑으로 배치)
462
+ with st.expander("⚙️ Rules Configuration", expanded=False):
463
+ st.caption("📝 웹 화면에서 수정·추가하면 시스템 파일에 영구 저장되어 연동됩니다.")
464
+ edited_rules = st.data_editor(st.session_state['rules_df'], num_rows="dynamic", use_container_width=True, hide_index=True, key="main_rules_editor")
465
+ if not edited_rules.equals(st.session_state['rules_df']):
466
+ st.session_state['rules_df'] = edited_rules
467
+ # 하드디스크 JSON 파일로 덮어쓰기 박제 (영구 저장의 핵심)
468
+ edited_rules.to_json(RULES_FILE, orient='records', force_ascii=False, indent=4)
469
+ st.toast("대출 매칭 규칙이 영구 저장되었습니다! 💾", icon="✅")
470
+
471
+ st.divider()
472
+
473
+ # Compliance Rules Data
474
+ if 'rules_df' not in st.session_state:
475
+ try:
476
+ st.session_state['rules_df'] = pd.read_excel('rules.xlsx')
477
+ except:
478
+ st.session_state['rules_df'] = pd.DataFrame(columns=['Stage Title', 'Sub 1', 'Sub 2', 'Keyword 1', 'Keyword 2'])
479
+
480
+ if 'status' not in st.session_state:
481
+ st.session_state['status'] = ["⚪"] * len(st.session_state['rules_df'])
482
+ # --- Helper Functions ---
483
+ def add_line_to_docx(paragraph):
484
+ p_ptr = paragraph._p.get_or_add_pPr()
485
+ p_bdr = OxmlElement('w:pBdr')
486
+ bottom = OxmlElement('w:bottom')
487
+ bottom.set(qn('w:val'), 'single'); bottom.set(qn('w:sz'), '4')
488
+ bottom.set(qn('w:space'), '1'); bottom.set(qn('w:color'), 'E2E8F0')
489
+ p_bdr.append(bottom); p_ptr.append(p_bdr)
490
+
491
+ def load_docs_from_path(path):
492
+ combined_text = ""
493
+ path = path.strip().replace('"', '')
494
+ if not os.path.exists(path): return None, f"Path not found: {path}"
495
+ files = [f for f in os.listdir(path) if f.lower().endswith(('.pdf', '.docx'))]
496
+ if not files: return None, "No reference docs found in the folder."
497
+ for f_name in files:
498
+ f_path = os.path.join(path, f_name)
499
+ try:
500
+ if f_name.lower().endswith('.pdf'):
501
+ with pdfplumber.open(f_path) as pdf:
502
+ for page in pdf.pages: combined_text += (page.extract_text() or "") + "\n"
503
+ elif f_name.lower().endswith('.docx'):
504
+ doc = Document(f_path)
505
+ for para in doc.paragraphs: combined_text += para.text + "\n"
506
+ except: continue
507
+ return combined_text, f"✅ Analyzed {len(files)} reference document(s)."
508
+
509
+ # 🟢 [콜백 삭제] 악명 높은 에러를 일으키는 assign_callback은 아예 삭제합니다!
510
+
511
+ # 🟢 메인 연산 함수: 상태 리스트를 '새 리스트 통째로 덮어쓰기'로 깔끔하게 유지
512
+ def update_status():
513
+ if st.session_state.get('results') is None: return
514
+
515
+ df = st.session_state['results']
516
+ rules = st.session_state['rules_df']
517
+ rules_list = rules.to_dict('records')
518
+
519
+ new_status = ["⚪"] * len(rules_list)
520
+
521
+ if st.session_state.get('active_mode') == "NOTION":
522
+ assigned = [re.sub(r'^\d+\.\s*', '', str(x)).lower().strip() for x in df[df['Type'] == "NOTION"]['Sec'].tolist()]
523
+
524
+ for idx, r in enumerate(rules_list):
525
+ stage_val = str(r.get('Stage Title', '')).strip().lower()
526
+ s1 = str(r.get('Sub 1', '')).strip().lower()
527
+ s2 = str(r.get('Sub 2', '')).strip().lower()
528
+
529
+ has_stage = stage_val not in ["", "nan", "x", "none", "-"]
530
+ has_s1 = s1 not in ["", "nan", "x", "none", "-"]
531
+ has_s2 = s2 not in ["", "nan", "x", "none", "-"]
532
+
533
+ is_stage_mapped = (stage_val in assigned) if has_stage else False
534
+ is_s1_mapped = (s1 in assigned) if has_s1 else False
535
+ is_s2_mapped = (s2 in assigned) if has_s2 else False
536
+
537
+ if is_stage_mapped:
538
+ new_status[idx] = "🟢"
539
+ else:
540
+ if has_s1 and not has_s2:
541
+ new_status[idx] = "🟢" if is_s1_mapped else "⚪"
542
+ elif has_s1 and has_s2:
543
+ if is_s1_mapped and is_s2_mapped: new_status[idx] = "🟢"
544
+ elif is_s1_mapped or is_s2_mapped: new_status[idx] = "🟠"
545
+ else: new_status[idx] = "⚪"
546
+ else:
547
+ new_status[idx] = "⚪"
548
+ else:
549
+ assigned = [str(x).lower().strip() for x in df[df['Type'] != "NOTION"]['Sec'].tolist()]
550
+
551
+ for idx, r in enumerate(rules_list):
552
+ s1 = str(r.get('Sub 1', '')).strip().lower()
553
+ s2 = str(r.get('Sub 2', '')).strip().lower()
554
+ has_s1 = s1 not in ["", "nan", "x", "None", "-"]
555
+ has_s2 = s2 not in ["", "nan", "x", "None", "-"]
556
+
557
+ is_s1_mapped = (s1 in assigned) if has_s1 else False
558
+ is_s2_mapped = (s2 in assigned) if has_s2 else False
559
+
560
+ if has_s1 and not has_s2:
561
+ new_status[idx] = "🟢" if is_s1_mapped else "⚪"
562
+ elif has_s1 and has_s2:
563
+ if is_s1_mapped and is_s2_mapped: new_status[idx] = "🟢"
564
+ elif is_s1_mapped or is_s2_mapped: new_status[idx] = "🟠"
565
+ else: new_status[idx] = "⚪"
566
+ else:
567
+ new_status[idx] = "⚪"
568
+
569
+ st.session_state['status'] = new_status
570
+ # --- Helper Functions ---
571
+ # (기존 add_line_to_docx, load_docs_from_path, update_status 등은 그대로 유지)
572
+
573
+ def ask_ai_note(stage_key, items_data, row_info, manual_note=""):
574
+ # 🚨 [파이썬 강력 통제 1] 매핑된 이메일 데이터가 단 한 개도 없고, 추가 수기 메모도 완전히 비어있다면
575
+ # AI 호출 자체를 생략하고 즉시 완벽한 3줄 공란을 리턴하여 비용과 오류를 원천 차단합니다.
576
+ if not items_data and not manual_note.strip():
577
+ return "Date: \nAction: \nPurpose: \n"
578
+
579
+ try:
580
+ #vertexai.init(project=st.secrets["PROJECT_ID"], location="us-west1")
581
+ from vertexai.generative_models import GenerativeModel
582
+ model = GenerativeModel('gemini-2.5-flash')
583
+
584
+ # 디지털 이메일/노션 소스 로그 포맷팅
585
+ context_str = ""
586
+ for i, m in enumerate(items_data):
587
+ record_type = m.get('Type', 'EMAIL')
588
+ d = m.get('Date', 'N/A')
589
+ b = m.get('Body', '')[:1500]
590
+
591
+ if record_type == "NOTION":
592
+ ch = m.get('Channel', '-')
593
+ cm = m.get('Comments', '')
594
+ context_str += f"Record {i+1} [Type: NOTION Task]\nDate: {d}\nChannel: {ch}\nDescription: {b}\nComments: {cm}\n\n"
595
+ else:
596
+ context_str += f"Record {i+1} [Type: EMAIL]\nDate: {d}\nBody: {b}\n\n"
597
+
598
+ # 규칙 데이터 안전 변환
599
+ rule_dict = dict(row_info) if row_info is not None else {}
600
+ stage_title = rule_dict.get('Stage Title', stage_key)
601
+ rule_action = rule_dict.get('Action', "").strip()
602
+ rule_purpose = rule_dict.get('Purpose', "").strip()
603
+
604
+ email_count = len(items_data)
605
+
606
+ # 🚨 [파이썬 강력 통제 2] 만약 디지털 매핑 데이터는 아예 없는데 '수기 메모'만 존재하는 경우,
607
+ # 이 수기 메모가 현재 순회 중인 단계와 연관이 있는 단어(예: 세미나, 첫 미팅 등)를 포함하는지 하드코딩으로 1차 검증합니다.
608
+ # 1번 INITIAL MEETING이 아닌 다른 단계에 미팅 정보가 침범하는 것을 완벽하게 막아냅니다.
609
+ if email_count == 0 and manual_note.strip():
610
+ lower_note = manual_note.lower()
611
+ # 1번 초기 미팅과 관련된 핵심 단어들 리스트
612
+ initial_keywords = ["initial", "meeting", "seminar", "remax", "처음", "만났", "미팅", "신분증", "얼굴"]
613
+
614
+ # 현재 단계가 1번 초기 미팅이 '아닌데', 수기 메모 내용이 초기 미팅 관련 내용뿐이라면 즉시 공란 리턴하고 차단
615
+ if "1." not in stage_key and any(kw in lower_note for kw in initial_keywords):
616
+ return "Date: \nAction: \nPurpose: \n"
617
+
618
+ # 🚨 [프롬프트 가드레일 개조]
619
+ prompt = f"""
620
+ You are a strict compliance auditor representing the New Zealand Financial Markets Authority (FMA).
621
+ Your job is to draft a professional File Note ONLY for the specific mortgage process stage: [{stage_title}]
622
+
623
+ [STRICT COMPLIANCE FILTERING MATRIX]
624
+ - Current Target Stage: {stage_title}
625
+ - Authorized Compliance Actions: {rule_action}
626
+ - Strategic Compliance Objective: {rule_purpose}
627
+
628
+ [REAL CLIENT DATA SETS (GROUND TRUTH)]
629
+ - Number of Digital Logs Matched: {email_count}
630
+ - Digital Logs (Matched Emails/Notion): {context_str if items_data else "NO DIGITAL LOGS FOR THIS STAGE"}
631
+ - User's Additional Memo: "{manual_note if manual_note.strip() else "NONE PROVIDED"}"
632
+
633
+ [⚠️ CRITICAL GENERATION RULES - DO NOT VIOLATE]
634
+ 1. MANDATORY OVERRIDE FOR MATCHED LOGS: If 'Number of Digital Logs Matched' is 1 or more, it means the user has manually verified and mapped these emails to [{stage_title}]. You MUST trust this mapping and generate a summary based on these logs.
635
+ 2. NO DATA = COMPLETE BLANK: If the provided digital logs are empty, and the User's Additional Memo does not explicitly describe a unique event for [{stage_title}], you are strictly forbidden from writing ANYTHING. You MUST output exactly this 3-line block and STOP. Do NOT copy the 'Strategic Compliance Objective' text into Purpose if there is no matching fact:
636
+ Date:
637
+ Action:
638
+ Purpose:
639
+ 3. NEVER COPY TEMPLATE TEXT: Do not copy-paste or mimic the phrase "{rule_action}" or "{rule_purpose}" into the note. Always write unique, professional descriptions based on the client logs.
640
+
641
+ [🚨 CRITICAL FORMAT RULE: NUMBER OF ITEMS MATCHING]
642
+ - CASE A (Single Source): If there is only 1 email/record matched, OR only the User's Memo is valid for this stage, output EXACTLY ONE pair of "Date:" and "Action:". (Do NOT use numbers like Date 1 or Action 1).
643
+ - CASE B (Multiple Sources): If there are 2 or more distinct emails/records matched, group them chronologically and use "Date 1:", "Action 1:", "Date 2:", "Action 2:" etc.
644
+
645
+ [PROPER FORMAT EXAMPLES]
646
+ Example for CASE A:
647
+ Date: 15 May 2026, 10:32 AM
648
+ Action: Sent an email to the client confirming the next steps of disclosure and requested verification docs.
649
+
650
+ Purpose: Written custom compliant rationale based on the real event.
651
+ """
652
+
653
+ response = model.generate_content(prompt)
654
+ res_text = response.text.strip()
655
+
656
+ if "Date: \nAction: \nPurpose:" in res_text or not res_text:
657
+ return "Date: \nAction: \nPurpose: \n"
658
+
659
+ return res_text
660
+
661
+ except Exception as e:
662
+ return f"⚠️ Vertex AI Error: {str(e)}"
663
+
664
+
665
+
666
+ # ─────────────────────────────────────────────────────────────────
667
+ # 🟢 [실시간 동기화 마법의 엔진] 사이드바를 그리기 전에 드롭다운 값을 먼저 가로채서 계산!
668
+ # ─────────────────────────────────────────────────────────────────
669
+ def sync_and_update_status():
670
+ if st.session_state.get('results') is None: return
671
+
672
+ # 1. 화면 맨 밑의 드롭다운(selectbox) 최신 값을 미리 가로채서 데이터프레임에 덮어씀
673
+ df = st.session_state['results']
674
+ for row_idx in df.index:
675
+ sel_key = f"sel_{row_idx}"
676
+ if sel_key in st.session_state:
677
+ df.at[row_idx, 'Sec'] = st.session_state[sel_key]
678
+
679
+ # 2. 전구(status) 즉시 계산
680
+ rules = st.session_state['rules_df']
681
+ rules_list = rules.to_dict('records')
682
+ new_status = ["⚪"] * len(rules_list)
683
+
684
+ if st.session_state.get('active_mode') == "NOTION":
685
+ assigned = [re.sub(r'^\d+\.\s*', '', str(x)).lower().strip() for x in df[df['Type'] == "NOTION"]['Sec'].tolist()]
686
+ for idx, r in enumerate(rules_list):
687
+ stage_val = str(r.get('Stage Title', '')).strip().lower()
688
+ s1 = str(r.get('Sub 1', '')).strip().lower()
689
+ s2 = str(r.get('Sub 2', '')).strip().lower()
690
+ has_stage = stage_val not in ["", "nan", "x", "none", "-"]
691
+ has_s1 = s1 not in ["", "nan", "x", "none", "-"]
692
+ has_s2 = s2 not in ["", "nan", "x", "none", "-"]
693
+
694
+ is_stage_mapped = (stage_val in assigned) if has_stage else False
695
+ is_s1_mapped = (s1 in assigned) if has_s1 else False
696
+ is_s2_mapped = (s2 in assigned) if has_s2 else False
697
+
698
+ if is_stage_mapped: new_status[idx] = "🟢"
699
+ else:
700
+ if has_s1 and not has_s2: new_status[idx] = "🟢" if is_s1_mapped else "⚪"
701
+ elif has_s1 and has_s2:
702
+ if is_s1_mapped and is_s2_mapped: new_status[idx] = "🟢"
703
+ elif is_s1_mapped or is_s2_mapped: new_status[idx] = "🟠"
704
+ else: new_status[idx] = "⚪"
705
+ else: new_status[idx] = "⚪"
706
+ else:
707
+ assigned = [str(x).lower().strip() for x in df[df['Type'] != "NOTION"]['Sec'].tolist()] if 'Type' in df.columns else [str(x).lower().strip() for x in df['Sec'].tolist()]
708
+ for idx, r in enumerate(rules_list):
709
+ s1 = str(r.get('Sub 1', '')).strip().lower()
710
+ s2 = str(r.get('Sub 2', '')).strip().lower()
711
+ has_s1 = s1 not in ["", "nan", "x", "None", "-"]
712
+ has_s2 = s2 not in ["", "nan", "x", "None", "-"]
713
+
714
+ is_s1_mapped = (s1 in assigned) if has_s1 else False
715
+ is_s2_mapped = (s2 in assigned) if has_s2 else False
716
+
717
+ if has_s1 and not has_s2: new_status[idx] = "🟢" if is_s1_mapped else "⚪"
718
+ elif has_s1 and has_s2:
719
+ if is_s1_mapped and is_s2_mapped: new_status[idx] = "🟢"
720
+ elif is_s1_mapped or is_s2_mapped: new_status[idx] = "🟠"
721
+ else: new_status[idx] = "⚪"
722
+ else: new_status[idx] = "⚪"
723
+
724
+ st.session_state['status'] = new_status
725
+
726
+ # 🚀 사이드바를 그리기 직전에 이 엔진을 무조건 가동시킵니다!
727
+ sync_and_update_status()
728
+
729
+ # --- [Sidebar Area: 통합 워드 스타일 에디터] ---
730
+ with st.sidebar:
731
+
732
+ # [1] Progress Status (상단 고정)
733
+ st.markdown("### 📊 Progress Status")
734
+ for row_idx in range(0, 10, 5):
735
+ cols = st.columns(5)
736
+ for i in range(5):
737
+ idx = row_idx + i
738
+ if idx < len(st.session_state['status']):
739
+ with cols[i]:
740
+ icon = st.session_state['status'][idx]
741
+ dt = "🟢" if icon == "🟢" else ("🟠" if icon == "🟠" else "⚪")
742
+ full_title = st.session_state['rules_df'].iloc[idx]['Stage Title']
743
+ st.markdown(
744
+ f"""<div style='text-align: center; line-height: 1.2; margin-bottom: 12px; min-height: 60px;'>
745
+ <div style='font-size: 1.1rem;'>{dt}</div>
746
+ <div style='font-size: 0.75rem; font-weight: bold; color: #1E3A8A;'>{idx+1}</div>
747
+ <div style='font-size: 0.65rem; color: #334155; word-break: keep-all; white-space: normal;'>{full_title}</div>
748
+ </div>""", unsafe_allow_html=True)
749
+
750
+ # ✨ [가이드 안내 문구 추가] 전구 상태 설명 및 AI 실행 안내 텍스트 이식
751
+ st.markdown("""
752
+ <div style='font-size: 0.73rem; color: #64748B; background-color: #F8FAFC; border: 1px solid #E2E8F0; padding: 10px 12px; border-radius: 6px; margin-top: 2px; margin-bottom: 18px; line-height: 1.5;'>
753
+ ⚪ <b>Unmapped</b> &nbsp;|&nbsp;
754
+ 🟠 <b>Partially Mapped (1/2)</b> &nbsp;|&nbsp;
755
+ 🟢 <b>Fully Mapped</b><br>
756
+ <div style='margin-top: 5px; color: #334155; font-weight: 600;'></div>
757
+ </div>
758
+ """, unsafe_allow_html=True)
759
+
760
+ # [수정 핵심] 변수 정의를 if문 밖으로 꺼내어 에러 방지
761
+ display_client = st.session_state.get('client_names', '').replace(';', ' & ').strip()
762
+ support_person = st.session_state.get('support_name', 'Edward Lee (BDM)')
763
+
764
+ # [2] 작업 버튼 영역 (Sync 완료 시에만 나타남)
765
+ if st.session_state.get('results') is not None:
766
+
767
+ # 🟢 [수정 2] UI 명칭 변경 및 프롬프트 역할 강조
768
+ ai_manual_note = st.text_area(
769
+ "💡 AI Additional Prompt (Optional)",
770
+ placeholder="AI에게 전달할 지시사항 (예: 전체 수집된 이메일 내역을 보고 Adviser note 알아서 생성 등)",
771
+ height=100
772
+ )
773
+
774
+ # 🟢 1. 현재 작업 중인 탭이 '이메일'인지 확인합니다.
775
+ current_mode = st.session_state.get('active_mode', 'NOTION')
776
+ is_email = (current_mode == "EMAIL")
777
+
778
+ # 🟢 2. 이메일 탭일 경우 체크박스를 강제로 끄고(False), 클릭 못 하게 잠급니다(disabled).
779
+ use_ai = st.checkbox(
780
+ "🤖 AI로 자동 작성하기 (API 비용 발생)",
781
+ value=False,
782
+ disabled=is_email,
783
+ help="🚫 이메일 모드에서는 AI 요약이 제한되며 빈 템플릿만 생성됩니다." if is_email else "체크를 끄면 비용 없이 날짜만 추출된 빈 템플릿이 즉시 생성됩니다."
784
+ )
785
+
786
+ col_ai, col_dl = st.columns(2)
787
+
788
+ with col_ai:
789
+
790
+ if st.button("✨ Run AI Summary", use_container_width=True):
791
+ with st.spinner("Adviser AI Generating Report..."):
792
+
793
+ # 🔄 [실시간 탭 감지 엔진] 현재 활성화된 모드에 따라 화면 입력값을 다이렉트로 추적
794
+ current_mode = st.session_state.get('active_mode', 'NOTION')
795
+
796
+ if current_mode == "NOTION":
797
+ # 노션 탭 입력창 값 가져와서 세미콜론 치환
798
+ raw_name = st.session_state.get('notion_client_name', '').strip()
799
+ final_client_name = raw_name.replace(';', ' & ') if raw_name else "N/A"
800
+ else:
801
+ # 이메일 탭 입력창 값 가져와서 세미콜론 치환
802
+ raw_name = st.session_state.get('client_names', '').strip()
803
+ final_client_name = raw_name.replace(';', ' & ') if raw_name else "N/A"
804
+
805
+ # 전역 변수에도 최신 상태 최종 박제 (워드 파일명 연동용)
806
+ st.session_state['global_client_name'] = final_client_name
807
+
808
+ # 상단 메타 헤더 정보 생성 (동적 추출된 이름 주입)
809
+ combined_content = f"ADVISER FILE NOTES LOG\n\nClient Name: {final_client_name}\nAdviser: Tim Park\nSupport: {st.session_state.get('support_name', 'N/A')}\nStatus: Completed / Final Approval Issued\n"
810
+ combined_content += "="*67 + "\n"
811
+
812
+ full_txt = st.session_state.get('full_note', '').strip()
813
+ if full_txt:
814
+ doc_bio = io.BytesIO()
815
+ final_doc = Document()
816
+
817
+ # [기존 기능 유지] 상단 메타 헤더 정보 생성
818
+ combined_content = f"ADVISER FILE NOTES LOG\n\nClient Name: {final_client_name}\nAdviser: Tim Park\nSupport: {st.session_state.get('support_name', 'N/A')}\nStatus: Completed / Final Approval Issued\n"
819
+ combined_content += "="*67 + "\n"
820
+
821
+ # [기존 기능 유지] 1. 화면상의 수동 매핑 상태(드롭다운 값)를 세션 데이터프레임에 동기화
822
+ if st.session_state.get('results') is not None:
823
+ for row_idx in st.session_state['results'].index:
824
+ sel_key = f"sel_{row_idx}"
825
+ if sel_key in st.session_state:
826
+ st.session_state['results'].at[row_idx, 'Sec'] = st.session_state[sel_key]
827
+
828
+ # [기존 기능 유지] 2. 현재 작업 모드(EMAIL 또는 NOTION)에 맞춰 소스 데이터 필터링
829
+ full_df = st.session_state['results'].copy() if st.session_state.get('results') is not None else pd.DataFrame()
830
+ if not full_df.empty:
831
+ if st.session_state.get('active_mode') == "NOTION":
832
+ df = full_df[full_df['Type'] == "NOTION"].copy()
833
+ else:
834
+ df = full_df[full_df['Type'] != "NOTION"].copy()
835
+ else:
836
+ df = pd.DataFrame(columns=['Sec', 'Type', 'Date', 'Body', 'Subject'])
837
+
838
+ # [기존 기능 유지] 실시간 규칙 세션 데이터셋 불러오기
839
+ rules_list = st.session_state['rules_df'].to_dict('records')
840
+
841
+ # 🚨 [동적 대응 업데이트] 고정된 10개가 아니라 웹에서 추가/삭제된 모든 단계를 실시간으로 유연하게 순회
842
+ for row in rules_list:
843
+ # 항목이 웹에서 동적으로 추가되더라도 에러가 나지 않도록 안전하게 변수 추출
844
+ r_no = row.get('No', '-')
845
+ r_title = row.get('Stage Title', 'Unknown Stage')
846
+ sk = f"{r_no}. {r_title}"
847
+
848
+ sub1 = str(row.get('Sub 1', '')).strip().lower()
849
+ sub2 = str(row.get('Sub 2', '')).strip().lower()
850
+ stage_title_lower = str(r_title).strip().lower()
851
+
852
+ # 🟢 [수정] 노션 데이터의 번호표("02. ", "03. " 등)를 떼어내고 정규화
853
+ temp_df = df.copy()
854
+ temp_df['Sec_Clean'] = temp_df['Sec'].astype(str).str.replace(r'^\d+\.\s*', '', regex=True).str.strip().str.lower()
855
+
856
+ # 🟢 [핵심] 수동 매핑(Sub 1, 2)과 노션 자동 매핑(Stage Title)을 모두 인정해 줍니다!
857
+ valid_targets = [sub1, sub2, stage_title_lower]
858
+ valid_targets = [x for x in valid_targets if x not in ["", "nan", "x", "none", "-"]]
859
+
860
+ targets = temp_df[temp_df['Sec_Clean'].isin(valid_targets)] if not temp_df.empty else pd.DataFrame()
861
+
862
+ combined_content += f"\n[{sk}]\n"
863
+
864
+ # [기존 기능 유지] 매핑된 이메일이 있거나, 혹은 이메일이 없더라도 사용자가 AI Additional Prompt를 적은 경우에만 AI 작동
865
+ if not targets.empty or ai_manual_note.strip():
866
+ e_data = targets.to_dict('records') if not targets.empty else []
867
+
868
+ # [기존 기능 유지] Ambiguous 에러 방지를 위해 row를 dict형으로 안전하게 변환하여 AI 호출
869
+ note_text = ask_ai_note(sk, e_data, dict(row), ai_manual_note)
870
+ combined_content += f"{note_text}\n\n"
871
+ else:
872
+ # [기존 기능 유지] 매핑된 이메일도 없고 추가 프롬프트 내용도 없는 구역은 깨끗하게 공란 폼만 출력
873
+ combined_content += "Date: \nAction: \nPurpose: \n\n"
874
+
875
+ # [기존 기능 유지] 최종 결과물을 사이드바 에디터 세션에 주입하고 화면 리프레시
876
+ st.session_state['full_note'] = combined_content
877
+ st.session_state['editor_version'] = datetime.now().strftime("%H%M%S")
878
+ st.rerun()
879
+
880
+
881
+ with col_dl:
882
+
883
+ # 🟢 전역 변수로 확정된 이름을 가져옵니다.
884
+ current_mode = st.session_state.get('active_mode', 'NOTION')
885
+
886
+ if current_mode == "NOTION":
887
+ raw_name = st.session_state.get('notion_client_name', '').strip()
888
+ final_client_name = raw_name.replace(';', ' & ') if raw_name else "N/A"
889
+ else:
890
+ raw_name = st.session_state.get('client_names', '').strip()
891
+ final_client_name = raw_name.replace(';', ' & ') if raw_name else "N/A"
892
+
893
+ full_txt = st.session_state.get('full_note', '').strip()
894
+ if full_txt:
895
+ doc_bio = io.BytesIO()
896
+ final_doc = Document()
897
+
898
+ # 워드 문서 전체 기본 폰트 설정
899
+ style = final_doc.styles['Normal']
900
+ font = style.font
901
+ font.name = 'Arial'
902
+ font.size = Pt(11)
903
+
904
+ lines = full_txt.split('\n')
905
+ for i, line in enumerate(lines):
906
+ # 1. 문서 제목 (가운데 정렬, 굵게, 크기 키움)
907
+ if line.strip() == "ADVISER FILE NOTES LOG":
908
+ p = final_doc.add_paragraph()
909
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
910
+ run = p.add_run(line.strip())
911
+ run.bold = True
912
+ run.font.size = Pt(16)
913
+ continue
914
+
915
+ # 2. 메타 정보 (이름, 어드바이저 등 항목 이름만 굵게 처리)
916
+ is_meta = False
917
+ for meta_key in ["Client Name:", "Adviser:", "Support:", "Status:"]:
918
+ if line.startswith(meta_key):
919
+ p = final_doc.add_paragraph()
920
+ parts = line.split(meta_key, 1)
921
+ run_bold = p.add_run(meta_key)
922
+ run_bold.bold = True
923
+ if len(parts) > 1:
924
+ p.add_run(parts[1])
925
+ is_meta = True
926
+ break
927
+ if is_meta:
928
+ continue
929
+
930
+ # 3. 최상단 실선 구분선 유지 (====)
931
+ if line.startswith('===='):
932
+ p_line = final_doc.add_paragraph(line)
933
+ p_line.paragraph_format.space_after = Pt(0)
934
+ continue
935
+
936
+ # 4. 각 섹션 제목 ([1. INITIAL MEETING] 등 파란색, 굵게)
937
+ if line.strip().startswith('[') and line.strip().endswith(']'):
938
+ if i > 10:
939
+ p_dash = final_doc.add_paragraph()
940
+ p_dash.add_run("-" * 117)
941
+
942
+ p = final_doc.add_paragraph()
943
+ run = p.add_run(line.strip())
944
+ run.bold = True
945
+ run.font.color.rgb = RGBColor(30, 58, 138)
946
+ run.font.size = Pt(12)
947
+ continue
948
+
949
+ # 5. 일반 텍스트 내 Date, Action, Purpose 라벨만 진하게 처리하는 구역
950
+ stripped_line = line.strip()
951
+ is_label_line = False
952
+
953
+ for target_label in ["Date", "Action", "Purpose"]:
954
+ if stripped_line.startswith(target_label):
955
+ p = final_doc.add_paragraph()
956
+ if ":" in stripped_line:
957
+ label_part, content_part = stripped_line.split(":", 1)
958
+ run_label = p.add_run(f"{label_part}:")
959
+ run_label.bold = True
960
+ p.add_run(content_part)
961
+ else:
962
+ run_all = p.add_run(stripped_line)
963
+ run_all.bold = True
964
+ is_label_line = True
965
+ break
966
+
967
+ if is_label_line:
968
+ continue
969
+
970
+ final_doc.add_paragraph(line)
971
+
972
+ final_doc.save(doc_bio)
973
+
974
+ # 🛠️ 수정: 안전하게 동기화된 final_client_name으로 파일명 빌드 및 다운로드 활성화
975
+ st.download_button("💾 Save Word", data=doc_bio.getvalue(), file_name=f"Adviser_File_Notes_Log_{final_client_name}.docx", use_container_width=True)
976
+ else:
977
+ st.button("💾 Save Word", use_container_width=True, disabled=True, help="Run AI Summary first")
978
+ st.divider()
979
+
980
+ # [3] 통합 텍스트 에디터 (중복 박스 제거, 텍스트 창만 유지)
981
+ if 'full_note' not in st.session_state: st.session_state['full_note'] = ""
982
+ ver = st.session_state.get('editor_version', 'default')
983
+
984
+ st.session_state['full_note'] = st.text_area(
985
+ label="Integrated Note Editor",
986
+ value=st.session_state['full_note'],
987
+ height=800,
988
+ key=f"final_editor_{ver}",
989
+ label_visibility="collapsed"
990
+ )
991
+ # --- [Main Area: Configuration] ---
992
+ st.title("📑 Flux Finance Internal Note")
993
+
994
+ # 💡 [세션 동기화 보강] 앱 초기 구동 시 액티브 모드가 비어있으면 기본값으로 이메일을 지정하여 락을 해제합니다.
995
+ if 'active_mode' not in st.session_state:
996
+ st.session_state['active_mode'] = "Notion"
997
+
998
+ # 💡 [탭 순서 혁신] 노션 탭을 배열의 맨 앞으로 배치하여 웹 접속 시 첫 화면에 무조건 노션 입력창이 먼저 뜨도록 제어합니다.
999
+ tab_notion, tab_email = st.tabs(["📝 Pull Notion", "✉️ Scan Emails"])
1000
+
1001
+ # TAB 1: 노션 검색창
1002
+ with tab_notion:
1003
+ with st.container(border=True):
1004
+ st.caption("💡 **Notion Sync:** Pull matching compliance tracks and thread messages.")
1005
+ c_notion1, c_notion2 = st.columns([5, 1])
1006
+ search_client = c_notion1.text_input("👤 Case Name (Applicants Name)", value=st.session_state['notion_client_name'], key="notion_search_bar_fixed_tab")
1007
+ st.session_state['notion_client_name'] = search_client
1008
+ notion_sync_btn = c_notion2.button("🔍 Pull", use_container_width=True, key="notion_sync_trigger")
1009
+
1010
+ if notion_sync_btn and search_client:
1011
+ st.session_state['active_mode'] = "NOTION"
1012
+ st.session_state['global_client_name'] = search_client.replace(';', ' & ').strip()
1013
+
1014
+ with st.status("🔍 Syncing Notion Workspace...", expanded=True) as status:
1015
+ # 🟢 리턴받은 case_comments를 세션에 저장
1016
+ tasks_data, msg, case_comments = fetch_client_tasks_from_notion(search_client)
1017
+
1018
+ if tasks_data:
1019
+ st.session_state['results'] = pd.DataFrame(tasks_data)
1020
+ st.session_state['results']['Type'] = "NOTION"
1021
+ st.session_state['case_comments'] = case_comments # 코멘트 세션 보관
1022
+
1023
+ update_status()
1024
+ status.update(label="✅ Notion Tasks Synced.", state="complete")
1025
+ st.rerun()
1026
+
1027
+ elif tasks_data is not None and not tasks_data:
1028
+ status.update(label="⚠️ 매칭 데이터 없음", state="error")
1029
+ else:
1030
+ status.update(label=f"❌ Failed: {msg}", state="error")
1031
+ # TAB 2: 이메일 검색창
1032
+ with tab_email:
1033
+ with st.container(border=True):
1034
+
1035
+ st.session_state['folder_path'] = st.text_input("📂 G: Drive Folder Path", value=st.session_state['folder_path'], key="fixed_mail_path")
1036
+
1037
+ # 🎯 [추가] secrets에서 주소만 쏙 발라내어 멀티 셀렉트 박스 생성
1038
+ raw_mailbox_list = st.secrets["company"].get("ALL_MAILBOXES", [])
1039
+ mailbox_options = []
1040
+ mailbox_map = {}
1041
+ for entry in raw_mailbox_list:
1042
+ entry_clean = entry.strip()
1043
+ if not entry_clean: continue
1044
+ cred_part = entry_clean.split("|")[0] if "|" in entry_clean else entry_clean
1045
+ clean_email = cred_part.split(":")[0].strip() if ":" in cred_part else cred_part.strip()
1046
+ mailbox_options.append(clean_email)
1047
+ mailbox_map[clean_email] = entry_clean
1048
+
1049
+ selected_boxes = st.multiselect("📬 Select Mailboxes to Scan", options=mailbox_options, default=[], key="active_mailboxes_select")
1050
+
1051
+
1052
+ c1, c2, c3, c4 = st.columns([2, 2, 1.5, 1])
1053
+ st.session_state['emails'] = c1.text_input("Emails", value=st.session_state['emails'], key="fixed_mail_addrs")
1054
+ st.session_state['client_names'] = c2.text_input("Names", value=st.session_state['client_names'], key="fixed_mail_names")
1055
+ st.session_state['refs'] = c3.text_input("Keywords", value=st.session_state['refs'], key="fixed_mail_refs")
1056
+
1057
+ email_sync_btn = c4.button("🚀 Sync Emails", use_container_width=True, key="email_sync_trigger")
1058
+ # ✨ [디자인 혁신] 투박한 안내 문구를 엔터프라이즈급 가이드 대시보드로 변경
1059
+ st.markdown("""
1060
+ <div style='background-color: #F8FAFC; border: 1px solid #E2E8F0; padding: 14px 18px; border-radius: 8px; margin-top: 15px;'>
1061
+ <div style='font-size: 0.85rem; font-weight: 700; color: #1E3A8A; margin-bottom: 4px;'>💡 System Usage Instructions</div>
1062
+ <div style='font-size: 0.8rem; color: #475569; margin-bottom: 12px;'>
1063
+ Use a semicolon (;) to search multiple items.</b>.
1064
+ </div>
1065
+ <div style='display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; border-top: 1px solid #E2E8F0; padding-top: 12px;'>
1066
+ <div>
1067
+ <span style='font-size: 0.72rem; font-weight: 800; background-color: #DBEAFE; color: #1E40AF; padding: 3px 6px; border-radius: 4px; letter-spacing: 0.5px;'>EMAILS SCOPE</span>
1068
+ <div style='font-size: 0.78rem; color: #64748B; margin-top: 6px; line-height: 1.4;'>Scans <b>From / To / CC</b> </div>
1069
+ </div>
1070
+ <div>
1071
+ <span style='font-size: 0.72rem; font-weight: 800; background-color: #E0F2FE; color: #0369A1; padding: 3px 6px; border-radius: 4px; letter-spacing: 0.5px;'>NAMES SCOPE</span>
1072
+ <div style='font-size: 0.78rem; color: #64748B; margin-top: 6px; line-height: 1.4;'>Scans <b>From / To / CC / Subject</b>.<br><span style='font-size: 0.72rem; color: #94A3B8;'>※ Order-agnostic full AND match</span></div>
1073
+ </div>
1074
+ <div>
1075
+ <span style='font-size: 0.72rem; font-weight: 800; background-color: #F1F5F9; color: #334155; padding: 3px 6px; border-radius: 4px; letter-spacing: 0.5px;'>KEYWORDS SCOPE</span>
1076
+ <div style='font-size: 0.78rem; color: #64748B; margin-top: 6px; line-height: 1.4;'>Scans <b>Subject / Body</b></div>
1077
+ </div>
1078
+ </div>
1079
+ </div>
1080
+ """, unsafe_allow_html=True)
1081
+
1082
+ if email_sync_btn:
1083
+ st.session_state['active_mode'] = "EMAIL"
1084
+ # 🟢 [여기에 추가] 이메일 이름을 전역 변수로 확정 박아버림! (여러 명이면 &로 치환)
1085
+ raw_names = st.session_state.get('client_names', '').strip()
1086
+ st.session_state['global_client_name'] = raw_names.replace(';', ' & ') if raw_names else ''
1087
+
1088
+ with st.status("🔍 Syncing...", expanded=True) as status:
1089
+ progress_text = st.empty()
1090
+ progress_text.info("Connecting and scanning emails... ⏳")
1091
+
1092
+ if st.session_state['folder_path']:
1093
+ txt, msg = load_docs_from_path(st.session_state['folder_path'])
1094
+ st.session_state['doc_context'] = txt if txt else ""; st.write(msg)
1095
+
1096
+ all_mails = []
1097
+ e_list = [e.strip().lower() for e in st.session_state['emails'].replace(";", ",").split(",") if "@" in e]
1098
+ name_groups = [[w.strip().lower() for w in n.replace(",", " ").split() if len(w.strip()) > 1] for n in st.session_state['client_names'].split(";")]
1099
+ ref_list = [r.strip().lower() for r in st.session_state['refs'].replace(";", ",").split(",") if len(r.strip()) > 3]
1100
+
1101
+ stats = {"count": 0}
1102
+ # 🎯 [교체 완료] 전체를 다 도는 대신, 멀티 셀렉트에서 선택된 사서함들만 추출
1103
+ target_mailbox_entries = [mailbox_map[m] for m in selected_boxes if m in mailbox_map]
1104
+
1105
+ if target_mailbox_entries:
1106
+ try:
1107
+ import email.utils
1108
+
1109
+ for entry in target_mailbox_entries:
1110
+ entry_clean = entry.strip()
1111
+ if not entry_clean: continue
1112
+
1113
+ if "|" in entry_clean:
1114
+ credential_part, imap_host = entry_clean.split("|", 1)
1115
+ imap_host = imap_host.replace("|", "").strip()
1116
+ else:
1117
+ credential_part = entry_clean
1118
+ imap_host = "arrow.mxrouting.net"
1119
+
1120
+ if ":" in credential_part:
1121
+ my_mail_addr, custom_pw = credential_part.split(":", 1)
1122
+ my_mail_addr = my_mail_addr.strip()
1123
+ target_pw = custom_pw.strip()
1124
+ else:
1125
+ my_mail_addr = credential_part.strip()
1126
+ target_pw = COMMON_PW
1127
+
1128
+ status.write(f"🔐 Scanning Mailbox: '{my_mail_addr}'...")
1129
+
1130
+ try:
1131
+ mail = IMAP4_SSL(imap_host, 993)
1132
+ mail.login(my_mail_addr, target_pw)
1133
+
1134
+ res_list, folder_list = mail.list()
1135
+ all_target_folders = []
1136
+
1137
+ if res_list == "OK":
1138
+ for f_info in folder_list:
1139
+ f_str = f_info.decode("utf-8", errors="ignore")
1140
+ # 🎯 [하위 폴더 공백/특수문자 파싱 버그 완벽 교정]
1141
+ # 폴더 전체 경로를 찢어 먹지 않고 쌍따옴표 구역을 역추적해 통째로 가져옵니다.
1142
+ if f_str.endswith('"'):
1143
+ last_quote = f_str.rfind('"')
1144
+ prev_quote = f_str.rfind('"', 0, last_quote)
1145
+ raw_folder_name = f_str[prev_quote+1 : last_quote]
1146
+ else:
1147
+ raw_folder_name = f_str.split()[-1].strip().strip('"')
1148
+
1149
+ if any(k in raw_folder_name.lower() for k in ["junk", "trash", "deleted", "sync", "spam"]):
1150
+ continue
1151
+ if raw_folder_name:
1152
+ all_target_folders.append(raw_folder_name)
1153
+
1154
+ if not all_target_folders:
1155
+ all_target_folders = ["INBOX", "Sent"]
1156
+
1157
+ for folder in all_target_folders:
1158
+ try:
1159
+ mail.select(f'"{folder}"', readonly=True)
1160
+ matched_ids = set()
1161
+ search_queries = []
1162
+
1163
+ # (A) Applicants Emails 쿼리 후보 수집
1164
+ for e_addr in e_list:
1165
+ clean_e = e_addr.strip()
1166
+ if clean_e:
1167
+ search_queries.append(f'(OR FROM "{clean_e}" (OR TO "{clean_e}" CC "{clean_e}"))')
1168
+
1169
+ # (B) Applicants Names 쿼리 후보 수집
1170
+ for group in name_groups:
1171
+ valid_words = [w.strip().replace(",", "") for w in group if len(w.strip()) > 1]
1172
+ for word in valid_words:
1173
+ if word:
1174
+ search_queries.append(f'(OR SUBJECT "{word}" (OR HEADER From "{word}" (OR HEADER To "{word}" HEADER Cc "{word}")))')
1175
+
1176
+ # (C) Ref Numbers 쿼리 후보 수집
1177
+ for r_num in ref_list:
1178
+ clean_r = r_num.strip()
1179
+ if clean_r:
1180
+ search_queries.append(f'TEXT "{clean_r}"')
1181
+
1182
+ # ⚡ [속도 혁신] 수집된 모든 개별 쿼리를 하나로 묶어 폴더당 단 1번만 서버에 요청 (1분 -> 3초 단축)
1183
+ if search_queries:
1184
+ combined_query = search_queries[0]
1185
+ for q in search_queries[1:]:
1186
+ combined_query = f'(OR {combined_query} {q})'
1187
+
1188
+ res, msg_ids = mail.search(None, combined_query)
1189
+ if msg_ids[0]:
1190
+ matched_ids.update(msg_ids[0].split())
1191
+
1192
+ if not matched_ids:
1193
+ continue
1194
+
1195
+ # 획득한 메일 번호 기반 본문 추출 엔진 정위치 안착
1196
+ for m_id in matched_ids:
1197
+ stats["count"] += 1
1198
+ res_body, body_data = mail.fetch(m_id, "(RFC822)")
1199
+ msg_raw = email.message_from_bytes(body_data[0][1])
1200
+
1201
+ subj = str(make_header(decode_header(msg_raw.get("Subject", ""))))
1202
+ snd = str(make_header(decode_header(msg_raw.get("From", ""))))
1203
+ to_header = str(msg_raw.get("To", ""))
1204
+
1205
+ # 💡 대소문자 통합 방어막 구축: Cc든 CC, cc든 대소문자 구분 없이 무조건 포획합니다.
1206
+ cc_raw = ""
1207
+ for header_key in msg_raw.keys():
1208
+ if header_key.lower() == "cc":
1209
+ cc_raw = msg_raw.get(header_key, "")
1210
+ break
1211
+
1212
+ cc_header = str(make_header(decode_header(str(cc_raw)))) if cc_raw else ""
1213
+
1214
+ body = ""
1215
+ if msg_raw.is_multipart():
1216
+ for b_part in msg_raw.walk():
1217
+ if b_part.get_content_type() == "text/plain":
1218
+ try:
1219
+ body = b_part.get_payload(decode=True).decode(errors='ignore')
1220
+ break
1221
+ except: pass
1222
+ else:
1223
+ try: body = msg_raw.get_payload(decode=True).decode(errors='ignore')
1224
+ except: body = "본문을 읽어올 수 없습니다."
1225
+
1226
+ attachments = []
1227
+ if msg_raw.is_multipart():
1228
+ for b_part in msg_raw.walk():
1229
+ filename = b_part.get_filename()
1230
+ if filename:
1231
+ decoded_filename = str(make_header(decode_header(filename)))
1232
+ attachments.append(decoded_filename)
1233
+
1234
+ dt = email.utils.parsedate_to_datetime(msg_raw.get("Date"))
1235
+
1236
+ # 🎯 [타임존 변환 버그 교정] 서버 시간(UTC)을 뉴질랜드(Auckland) 현지 시간으로 정확하게 강제 변환합니다.
1237
+ if dt and dt.tzinfo:
1238
+ try:
1239
+ from zoneinfo import ZoneInfo
1240
+ dt = dt.astimezone(ZoneInfo("Pacific/Auckland"))
1241
+ except:
1242
+ dt = dt.astimezone(None)
1243
+
1244
+ # 🎯 각 항목별 검색 구역을 완벽하게 분리
1245
+ email_area = (snd + " " + to_header + " " + cc_header).lower()
1246
+ name_area = (subj + " " + snd + " " + to_header + " " + cc_header).lower()
1247
+ ref_area = (subj + " " + body).lower()
1248
+
1249
+ # 1. 이메일 주소는 오직 From, To, CC 영역에서만 매칭 (OR)
1250
+ email_matched = any(e_addr in email_area for e_addr in e_list) if e_list else False
1251
+
1252
+ # 2. 대출 참조 번호는 오직 제목(Subject)과 본문(Body) 영역에서만 매칭 (OR)
1253
+ ref_matched = any(r_num in ref_area for r_num in ref_list) if ref_list else False
1254
+
1255
+ # 3. 이름은 From, To, CC, Subject 영역에서 검사하되, 성과 이름 단어가 '순서 상관없이 모두(AND)' 존재해야 함!
1256
+ name_matched = False
1257
+ if name_groups and any(len(g) > 0 for g in name_groups):
1258
+ for group in name_groups:
1259
+ # 예: 'misun'과 'lim'이 이름 검사 영역에 동시에 다 들어있어야만 true! (Misun Kim 차단)
1260
+ if group and all(word in name_area for word in group):
1261
+ name_matched = True
1262
+ break
1263
+
1264
+ # 4. 세 카테고리(이메일 주소 vs 대출번호 vs 이름) 간의 최종 관계는 완전한 OR
1265
+ if email_matched or name_matched or ref_matched:
1266
+ all_mails.append({
1267
+ "Date": dt.strftime("%d %b %Y, %I:%M %p"),
1268
+ "Subject": subj,
1269
+ "From": snd,
1270
+ "To": to_header,
1271
+ "Cc": cc_header,
1272
+ "Type": "SENT" if any(dom in snd.lower() for dom in ["fluxfinance.co.nz", "ewfinance.co.nz"]) else "RECEIVED",
1273
+ "Body": body,
1274
+ "Sec": "-",
1275
+ "Attach": attachments,
1276
+ "RawDate": dt.replace(tzinfo=None)
1277
+ })
1278
+ except: continue
1279
+ mail.logout()
1280
+ except: pass
1281
+ except Exception as e:
1282
+ st.error(f"IMAP Engine Error: {e}")
1283
+
1284
+ if all_mails:
1285
+ all_mails.sort(key=lambda x: x.get("RawDate", datetime.min))
1286
+ df = pd.DataFrame(all_mails).drop_duplicates(subset=['Subject', 'Date'])
1287
+ st.session_state['results'] = df.reset_index(drop=True)
1288
+
1289
+ assigned = st.session_state['results']['Sec'].tolist()
1290
+ for idx, r in st.session_state['rules_df'].iterrows():
1291
+ s1 = str(r.get('Sub 1', '')).strip()
1292
+ s2 = str(r.get('Sub 2', '')).strip()
1293
+ has_s1 = s1 not in ["", "nan", "x", "None", "-"]
1294
+ has_s2 = s2 not in ["", "nan", "x", "None", "-"]
1295
+ is_s1_mapped = s1 in assigned if has_s1 else False
1296
+ is_s2_mapped = s2 in assigned if has_s2 else False
1297
+ if has_s1 and not has_s2: st.session_state['status'][idx] = "🟢" if is_s1_mapped else "⚪"
1298
+ elif has_s1 and has_s2:
1299
+ if is_s1_mapped and is_s2_mapped: st.session_state['status'][idx] = "🟢"
1300
+ elif is_s1_mapped or is_s2_mapped: st.session_state['status'][idx] = "🟠"
1301
+ else: st.session_state['status'][idx] = "⚪"
1302
+ else: st.session_state['status'][idx] = "⚪"
1303
+
1304
+ status.update(label=f"✅ Scan complete! Found {len(all_mails)} matching email(s).", state="complete", expanded=False)
1305
+ else:
1306
+ st.session_state['results'] = None
1307
+ progress_text.error(f"Checked {stats['count']} emails. No matches found.")
1308
+
1309
+ # ─────────────────────────────────────────────────────────────────
1310
+ # 🎯 [4단계] 통합 결과창 드로잉 레이아웃
1311
+ # ─────────────────────────────────────────────────────────────────
1312
+ if st.session_state['results'] is not None:
1313
+ update_status()
1314
+ for idx, row in st.session_state['results'].iterrows():
1315
+ # 모드 필터링
1316
+ if st.session_state['active_mode'] == "NOTION" and row.get('Type') != "NOTION": continue
1317
+ if st.session_state['active_mode'] == "EMAIL" and row.get('Type') == "NOTION": continue
1318
+
1319
+ with st.container(border=True):
1320
+ # [1] 타입별 상단 헤더 출력 (유지)
1321
+ if row['Type'] == "NOTION":
1322
+ st.markdown(f"<span class='type-tag notion-tag'></span> <b>📌 Stage: {row['Sec']}</b>",
1323
+ unsafe_allow_html=True
1324
+ )
1325
+ # 🟢 날짜 옆에 Channel 값을 함께 출력합니다.
1326
+ channel_info = str(row.get('Channel', '-')).strip()
1327
+ st.markdown(f"""
1328
+ <div style='font-size: 0.88rem; font-weight: 600; color: #1E3A8A; margin-top: 6px; margin-bottom: 4px;'>
1329
+ 📅 Completed On: {row['Date']} &nbsp;&nbsp;|&nbsp;&nbsp; 📡 Channel: <span style='color: #059669;'>{channel_info}</span>
1330
+ </div>
1331
+ """, unsafe_allow_html=True)
1332
+ else:
1333
+ # 1. 태그와 제목 출력
1334
+ st.markdown(f"<span class='type-tag {'sent' if row['Type']=='SENT' else 'received'}'>{row['Type']}</span> **{row['Subject']}**", unsafe_allow_html=True)
1335
+
1336
+ # 2. 날짜를 상단에 단독 배치
1337
+ st.markdown(f"<div style='font-size: 0.88rem; font-weight: 600; color: #1E3A8A; margin-top: 6px; margin-bottom: 4px;'>📅 {row['Date']}</div>", unsafe_allow_html=True)
1338
+
1339
+ # 3. From, To, CC 각각 개별 줄바꿈
1340
+ cc_value = str(row.get('Cc', '')).strip()
1341
+ cc_display = cc_value if cc_value and cc_value.lower() != 'nan' else "<span style='color: #94a3b8; font-style: italic;'>None</span>"
1342
+
1343
+ st.markdown(f"""
1344
+ <div style='font-size: 0.85rem; color: #64748b; line-height: 1.6; margin-bottom: 12px;'>
1345
+ <b>From:</b> {row['From']}<br>
1346
+ <b>To:</b> {row['To']}<br>
1347
+ <b>CC:</b> {cc_display}
1348
+ </div>
1349
+ """, unsafe_allow_html=True)
1350
+
1351
+ # 💡 [두 번째 if NOTION]: 매핑 상태 (배지 vs 드롭다운) 처리 구역
1352
+ rules = st.session_state['rules_df']
1353
+ rules_list = rules.to_dict('records')
1354
+
1355
+ # 🚨 [기능 추가] 웹에서 실시간으로 추가/수정된 모든 단계를 드롭다운 옵션에 자동 반영
1356
+ opts = ["-"]
1357
+ for _, r in rules.iterrows():
1358
+ s1 = str(r.get('Sub 1', '')).strip()
1359
+ s2 = str(r.get('Sub 2', '')).strip()
1360
+ if s1 and s1 not in ['nan', 'x', '', 'None', '-'] and s1 not in opts: opts.append(s1)
1361
+ if s2 and s2 not in ['nan', 'x', '', 'None', '-'] and s2 not in opts: opts.append(s2)
1362
+
1363
+ # 웹 설정에서 새로 수정한 값이나 기존 값이 opts 배열에 누수되었을 경우를 방지하는 실시간 안전망
1364
+ current_sec_val = str(row.get('Sec', '-')).strip()
1365
+ if current_sec_val not in opts and current_sec_val != "-":
1366
+ opts.insert(1, current_sec_val)
1367
+
1368
+ if row['Type'] == "NOTION":
1369
+ clean_raw = re.sub(r'^\d+\.\s*', '', str(row['RawTitle'])).strip().lower()
1370
+ stage_titles = [str(x).strip().lower() for x in rules['Stage Title'].tolist()]
1371
+
1372
+ if clean_raw in stage_titles:
1373
+ # 🟢 [기존 기능 유지] 일치함: 자동 매핑 배지 표시
1374
+ matched_stage_idx = stage_titles.index(clean_raw)
1375
+ matched_stage_name = rules['Stage Title'].iloc[matched_stage_idx]
1376
+ st.markdown(f"""
1377
+ <div style='background-color: #F0F9FF; padding: 6px 12px; border-radius: 6px;
1378
+ border: 1px solid #BAE6FD; font-size: 0.85rem; color: #0369A1; font-weight: 600; margin: 10px 0;'>
1379
+ ✅ Auto-Mapped: {matched_stage_name}
1380
+ </div>
1381
+ """, unsafe_allow_html=True)
1382
+ else:
1383
+ # ⚠️ [기존 기능 유지] 일치하지 않음: 수동 할당을 위한 경고 배지 및 드롭다운 활성화
1384
+ st.markdown("<div style='font-size: 0.75rem; color: #EF4444; margin-bottom: 4px; font-weight: bold;'>⚠️ Unmapped (Assign Manually)</div>", unsafe_allow_html=True)
1385
+ st.selectbox("Assign Action", opts, index=opts.index(current_sec_val) if current_sec_val in opts else 0, key=f"sel_{idx}", label_visibility="collapsed")
1386
+ else:
1387
+ # 🟢 [기존 기능 유지] 이메일 전용: 수동 할당 드롭다운
1388
+ st.selectbox("Assign Action", opts, index=opts.index(current_sec_val) if current_sec_val in opts else 0, key=f"sel_{idx}", label_visibility="collapsed")
1389
+
1390
+ # [기존 기능 유지] 본문(Body) 출력
1391
+ st.markdown(f"<div class='content-box'>{row.get('Body', '')}</div>", unsafe_allow_html=True)
1392
+
1393
+ # 🟢 [기존 기능 유지] 코멘트(Comments)가 있을 경우, 본문 아래에 별도의 말풍선 박스로 예쁘게 렌더링
1394
+ comments_data = row.get('Comments', '').strip()
1395
+ if comments_data:
1396
+ html_comments = comments_data.replace('\n', '<br>')
1397
+ st.markdown(f"""
1398
+ <div style='background-color: #FEF3C7; padding: 12px 15px; border-radius: 8px; border: 1px solid #FCD34D; font-size: 0.85rem; margin-top: 12px; color: #92400E; line-height: 1.6;'>
1399
+ <b>💬 Notion Comments:</b><br><br>{html_comments}
1400
+ </div>
1401
+ """, unsafe_allow_html=True)
1402
+
1403
+ # [기존 기능 유지] 첨부파일 출력 구역
1404
+ if row.get('Attach'):
1405
+ st.markdown(f"<div class='attach-box'>📎 <b>Attachments:</b> {', '.join(row['Attach'])}</div>", unsafe_allow_html=True)