Spaces:
Sleeping

File size: 31,935 Bytes
56387c5
42d5af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44fb52a
42d5af1
44fb52a
42d5af1
 
 
 
 
 
 
 
 
 
 
 
c6e847d
 
7d482e6
 
 
 
 
 
 
 
 
 
 
42d5af1
c6e847d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42d5af1
 
 
 
 
 
 
 
 
d5d5a62
 
 
 
44fb52a
 
a1928d3
d5d5a62
f7f80d0
d5d5a62
 
 
 
 
 
42d5af1
 
 
 
 
 
 
 
 
 
 
d5d5a62
 
 
 
 
44fb52a
 
a1928d3
d5d5a62
f7f80d0
d5d5a62
 
 
42d5af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0ba57c
42d5af1
 
 
 
 
 
 
 
e0ba57c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5d5a62
42d5af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0ba57c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42d5af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c872572
42d5af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5d5a62
 
 
 
42d5af1
e0ba57c
42d5af1
e0ba57c
42d5af1
 
 
 
 
 
 
 
 
b807a25
 
42d5af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56387c5
42d5af1
 
 
 
 
 
 
 
 
 
ef591ce
42d5af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
import streamlit as st
import pandas as pd
import requests
from bs4 import BeautifulSoup
import json
from datetime import timedelta, timezone
import datetime 
from supabase import create_client, Client
import time
import re
import os
import extra_streamlit_components as stx
import plotly.express as px
import streamlit.components.v1 as components

# --- 頁面基本設定 ---
st.set_page_config(page_title="錢進自由", layout="wide", page_icon="📈", initial_sidebar_state="collapsed")

# ==========================================
# 📱 🚀 手機版視覺優化 CSS + 👻 隱藏 UI 終極版
# ==========================================
st.markdown("""
    <style>
    html, body, [class*="css"] { font-family: 'PingFang TC', 'Microsoft JhengHei', sans-serif; }
    
    @media (max-width: 768px) {
        div[data-testid="stColumns"],
        div[data-testid="stHorizontalBlock"],
        div[data-testid="stColumnLayout"],
        div[class*="stColumns"],
        div[class*="stHorizontalBlock"] {
            display: flex !important;
            flex-direction: row !important;
            flex-wrap: nowrap !important;
            align-items: stretch !important;
            gap: 6px !important;
        }
        
        div[data-testid="stColumn"],
        div[data-testid="column"],
        div[class*="stColumn"] {
            flex: 1 1 0% !important;
            width: 100% !important;
            min-width: 0 !important;
            padding: 0 !important;
            display: block !important;
        }
        
        .stButton button { 
            height: 38px !important; 
            min-height: 38px !important;
            max-height: 38px !important;
            padding: 0px !important; 
            font-size: 18px !important; 
            width: 100% !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            border-radius: 6px !important;
            margin: 0 !important;
        }

        [data-testid="stMetricValue"] {
            font-size: 1.4rem !important; 
            white-space: normal !important; 
            word-wrap: break-word !important;
            line-height: 1.1 !important;
        }
        [data-testid="stMetricLabel"] {
            font-size: 11px !important;
        }
        
        .block-container { 
            padding-top: 1rem !important; 
            padding-bottom: 0rem !important; 
        }
        .stTabs [data-baseweb="tab"] { 
            padding-left: 5px !important; 
            padding-right: 5px !important; 
            font-size: 14px !important; 
        }
    }

    /* 👻 徹底消滅不必要的 UI 與按鈕 */
    [data-testid="stHeader"] { display: none !important; }
    [data-testid="stToolbar"] { display: none !important; }
    [data-testid="stDecoration"] { display: none !important; }
    [data-testid="stFooter"], footer { display: none !important; }
    [data-testid="manage-app-button"], ._terminalButton_rix23_138, [class^="viewerBadge"] { display: none !important; }
    [data-testid="stNumberInputStepUp"], [data-testid="stNumberInputStepDown"], button[aria-label="Step down"], button[aria-label="Step up"] { display: none !important; }
    input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button { -webkit-appearance: none !important; margin: 0 !important; }
    input[type="number"] { -moz-appearance: textfield !important; }

    /* 🌀 專屬載入動畫 CSS */
    .my-spinner {
        width: 50px; height: 50px; border: 5px solid #f3f3f3; border-top: 5px solid #003366;
        border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto;
    }
    @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
""", unsafe_allow_html=True)

# ==========================================
# 💱 即時匯率 API (擷取 USD/TWD)
# ==========================================
@st.cache_data(ttl=3600)  
def get_usd_twd_rate():
    try:
        res = requests.get("https://api.exchangerate-api.com/v4/latest/USD", timeout=3)
        return float(res.json()["rates"]["TWD"])
    except:
        return 32.0 

usd_twd_rate = get_usd_twd_rate()

# ==========================================
# 🍪 系統初始化與登入
# ==========================================
cookie_manager = stx.CookieManager(key="my_cookies")

@st.cache_resource
def init_supabase() -> Client:
    return create_client(os.environ.get("SUPABASE_URL"), os.environ.get("SUPABASE_KEY"))

supabase = init_supabase()

def login_ui():
    if "user_email" in st.session_state: return True
    cookies = cookie_manager.get_all()
    
    saved_email = cookies.get("user_email") if isinstance(cookies, dict) else None
    if saved_email:
        st.session_state["user_email"] = saved_email
        return True
        
    st.markdown("<h1 style='text-align: center; color: #003366; margin-top: 40px;'>🛋️ 錢進自由</h1>", unsafe_allow_html=True)
    
    # 💡 放大版、高質感的安全聲明與提示方塊
    st.markdown("""
    <div style='background-color: #f4f8fb; padding: 20px; border-radius: 12px; margin-bottom: 25px; border-left: 6px solid #1f77b4; box-shadow: 0 2px 4px rgba(0,0,0,0.05);'>
        <p style='font-size: 17px; line-height: 1.6; color: #2c3e50; margin-bottom: 12px;'>
            <b>💡 為改善登入機制,請老朋友使用您「原本登入的Google信箱」作為帳號進行註冊,系統將自動無縫還原您所有的歷史資產資料!</b>
        </p>
        <p style='font-size: 15px; line-height: 1.6; color: #555555; margin: 0;'>
            🔒 所有使用者的密碼均由國際級資料庫 Supabase 進行高強度加密儲存,本網站及系統管理員絕對無法得知您的密碼,請安心設定並使用。
        </p>
    </div>
    """, unsafe_allow_html=True)
    
    # 📝 帳號密碼輸入表單
    with st.form("login_form"):
        email = st.text_input("✉️ 電子信箱 (Email)", placeholder="請輸入信箱")
        password = st.text_input("🔑 密碼 (Password)", type="password", placeholder="請輸入密碼 (至少 6 位數)")
        
        c1, c2 = st.columns(2)
        btn_login = c1.form_submit_button("🚀 登入", use_container_width=True)
        btn_signup = c2.form_submit_button("📝 註冊新帳號", use_container_width=True)

    if btn_login:
        if not email or not password:
            st.warning("⚠️ 請輸入信箱與密碼!")
        else:
            try:
                res = supabase.auth.sign_in_with_password({"email": email, "password": password})
                st.session_state["user_email"] = res.user.email
                cookie_manager.set("user_email", res.user.email, max_age=30*24*60*60)
                st.rerun()
            except Exception as e:
                st.error("🛑 登入失敗:請確認信箱與密碼是否正確。若為首次使用,請先點擊「註冊新帳號」。")

    if btn_signup:
        if not email or len(password) < 6:
            st.warning("⚠️ 請輸入信箱,且密碼需至少 6 位數!")
        else:
            try:
                res = supabase.auth.sign_up({"email": email, "password": password})
                if res.user:
                    st.success("🎉 註冊成功!系統正在為您登入...")
                    st.session_state["user_email"] = res.user.email
                    cookie_manager.set("user_email", res.user.email, max_age=30*24*60*60)
                    time.sleep(1)
                    st.rerun()
            except Exception as e:
                st.error(f"🛑 註冊失敗:此信箱可能已被註冊,或密碼格式不符。({e})")

    return False

if not login_ui(): st.stop()

# ==========================================
# 🗄️ 資料庫讀寫與自動補齊
# ==========================================
user_email = st.session_state["user_email"]
def load_data():
    try:
        res = supabase.table("user_data").select("*").eq("email", user_email).execute()
    except Exception as e:
        if "JWT expired" in str(e) or "PGRST303" in str(e):
            try: supabase.auth.sign_out() 
            except: pass
            cookie_manager.delete("user_email", key="del_load")
            st.session_state.clear()
            init_supabase.clear() 
            st.error("🔒 系統安全機制:登入時效已過期,請重新登入!")
            time.sleep(2)
            st.rerun()
        else:
            raise e

    defaults = {"fee_discount": 6.0, "us_stock_fee": 0.0, "pledge_amount": 0.0, "account_balance": 0.0, "usd_balance": 0.0, "credit_loan": 0.0, "mortgage_amount": 0.0, "other_assets": 0.0, "buy_records": [], "realized_records": [], "history": {}, "market_data": {}, "futures_capital": 0.0}
    if len(res.data) == 0:
        supabase.table("user_data").insert({"email": user_email, "data": defaults}).execute()
        return defaults
    data = res.data[0]["data"]
    updated = False
    for k, v in defaults.items():
        if k not in data: data[k] = v; updated = True
    if updated: save_data(data)
    return data

def save_data(data): 
    try:
        supabase.table("user_data").update({"data": data}).eq("email", user_email).execute()
    except Exception as e:
        if "JWT expired" in str(e) or "PGRST303" in str(e):
            try: supabase.auth.sign_out() 
            except: pass
            cookie_manager.delete("user_email", key="del_save")
            st.session_state.clear()
            init_supabase.clear()
            st.rerun()
        else:
            raise e

db = load_data()

# --- 🚀 爬蟲與精算引擎 ---
def fetch_price(ticker):
    price, name = 0.0, ticker
    t_l = ticker.lower()
    for url, tag in [(f"https://www.wantgoo.com/stock/{t_l}", 'span')]:
        try:
            resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=5)
            soup = BeautifulSoup(resp.text, 'html.parser')
            node = soup.find(tag, class_='deal', attrs={'c-model': 'close'})
            if node and node.text.strip() != "--":
                price = float(node.text.replace(',', ''))
                nh3 = soup.find('h3', attrs={'c-model': 'name'})
                if nh3: name = nh3.text.strip()
                break
        except: pass
        
    if price == 0.0:
        try:
            url_y = f"https://tw.stock.yahoo.com/quote/{ticker}"
            resp_y = requests.get(url_y, headers={'User-Agent': 'Mozilla/5.0'}, timeout=5)
            soup_y = BeautifulSoup(resp_y.text, 'html.parser')
            if name == ticker:
                title_tag = soup_y.find('title')
                if title_tag: name = title_tag.text.split('(')[0].strip().replace("Yahoo", "").strip()
            match = re.search(r'"regularMarketPrice":([0-9.]+)', resp_y.text)
            if match: price = float(match.group(1))
        except: pass
    return price, name

def calc_cost_profit(ticker, shares, buy_price, sell_price=None, is_foreign=False):
    buy_cost = shares * buy_price
    
    if is_foreign:
        us_fee = float(db.get("us_stock_fee", 0.0))
        buy_fee = us_fee
        total_cost = buy_cost + buy_fee
        if sell_price is not None:
            sell_rev = shares * sell_price
            sell_fee = us_fee
            return round(sell_rev - sell_fee - total_cost)
        return total_cost
    else:
        disc = db.get("fee_discount", 6.0) / 10.0
        buy_fee = buy_cost * 0.001425 * disc
        total_cost = buy_cost + buy_fee
        if sell_price is not None:
            sell_rev = shares * sell_price
            sell_fee = sell_rev * 0.001425 * disc
            tax_rate = 0.001 if ticker.startswith("00") else 0.003
            sell_tax = sell_rev * tax_rate
            return round(sell_rev - sell_fee - sell_tax - total_cost)
        return total_cost

# ==========================================
# 🛑 彈出對話框定義
# ==========================================
@st.dialog("🔔 系統提示")
def show_success_dialog():
    st.markdown(f"<div style='font-size: 16px; margin-bottom: 20px; line-height: 1.5;'>{st.session_state['success_msg']}</div>", unsafe_allow_html=True)
    if st.button("確定", type="primary", use_container_width=True):
        del st.session_state["success_msg"]
        st.rerun()

# 💡 新增:防呆登出確認視窗
@st.dialog("🚪 系統登出")
def confirm_logout():
    st.markdown("<div style='font-size: 16px; margin-bottom: 20px; text-align: center;'>確定要登出戰情室嗎?</div>", unsafe_allow_html=True)
    c1, c2 = st.columns(2)
    if c1.button("取消", use_container_width=True):
        st.rerun()
    if c2.button("確認登出", type="primary", use_container_width=True):
        try: supabase.auth.sign_out() 
        except: pass
        cookie_manager.delete("user_email", key="del_logout_confirm")
        st.session_state.clear()
        init_supabase.clear() 
        components.html("""<script>document.cookie = "user_email=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; setTimeout(function() {window.parent.location.reload();}, 300);</script>""", height=0)
        st.stop()

@st.dialog("⚙️ 設定中心")
def show_settings():
    new_disc = st.number_input("台股手續費折數", value=float(db.get("fee_discount", 6.0)))
    new_us_fee = st.number_input("美股手續費 (單筆/美元)", value=float(db.get("us_stock_fee", 0.0)))
    if st.button("💾 儲存並關閉", type="primary", use_container_width=True):
        db["fee_discount"] = new_disc
        db["us_stock_fee"] = new_us_fee
        save_data(db); st.rerun()

@st.dialog("➕ 新增股票")
def add_stock():
    d = st.date_input("日期")
    t = st.text_input("股票代號", placeholder="如2330、00631L、VOO、AAPL等代號").upper()
    s = st.number_input("股數", min_value=1, step=1)
    p = st.number_input("成交價 (原幣別)", min_value=0.01)
    if st.button("確認新增", type="primary", use_container_width=True):
        if t:
            pr, na = fetch_price(t); db["market_data"][t] = {"price": pr, "name": na}
            db["buy_records"].append({"id": int(time.time()), "date": str(d), "ticker": t, "shares": s, "price": p})
            save_data(db)
            st.session_state["success_msg"] = "✅ 新增成功,記得去手動更新銀行帳戶餘額哦!"
            st.rerun()

@st.dialog("🔍 股票明細")
def show_details(ticker, name):
    recs = sorted([r for r in db["buy_records"] if r["ticker"] == ticker], key=lambda x: x["date"], reverse=True)
    for r in recs:
        c1, c2, c3, c4 = st.columns([2, 2, 2, 1])
        c1.write(r["date"]); c2.write(f"{r['shares']:,}"); c3.write(f"${r['price']:.2f}")
        if c4.button("🗑️", key=f"del_{r['id']}"):
            db["buy_records"] = [x for x in db["buy_records"] if x["id"] != r["id"]]
            save_data(db); st.rerun()

@st.dialog("🛒 賣出股票")
def sell_stock(ticker, name):
    is_foreign = not ticker[0].isdigit()
    tot_s = sum(r["shares"] for r in db["buy_records"] if r["ticker"] == ticker)
    sd, ss = st.date_input("賣出日期"), st.number_input("股數", min_value=1, max_value=tot_s, step=1)
    sp = st.number_input("單價 (原幣別)", value=float(db["market_data"].get(ticker, {"price": 0.0})["price"]))
    
    if st.button("確認賣出", type="primary", use_container_width=True):
        rem = ss
        total_net_cash_native = 0 
        
        for r in sorted([x for x in db["buy_records"] if x["ticker"] == ticker], key=lambda x: x["date"]):
            if rem <= 0: break
            take = min(r["shares"], rem)
            
            if is_foreign:
                sell_rev = take * sp
                sell_fee = float(db.get("us_stock_fee", 0.0))
                sell_tax = 0.0
            else:
                disc = db.get("fee_discount", 6.0) / 10.0
                sell_rev = take * sp
                sell_fee = sell_rev * 0.001425 * disc
                tax_rate = 0.001 if ticker.startswith("00") else 0.003
                sell_tax = sell_rev * tax_rate
            
            batch_net_cash = sell_rev - sell_fee - sell_tax
            total_net_cash_native += batch_net_cash
            
            db["realized_records"].append({"sell_date": str(sd), "ticker": ticker, "shares": take, "buy_price": r["price"], "sell_price": sp})
            r["shares"] -= take; rem -= take
            
        db["buy_records"] = [x for x in db["buy_records"] if x["shares"] > 0]
        
        if is_foreign:
            db["usd_balance"] = float(db.get("usd_balance", 0.0)) + total_net_cash_native
            st.session_state["success_msg"] = f"✅ 賣出成功!<br>淨額 <b>${total_net_cash_native:,.2f} USD</b> (已扣手續費)<br>已自動加入「美元帳戶餘額」!"
        else:
            db["account_balance"] = float(db.get("account_balance", 0.0)) + total_net_cash_native
            st.session_state["success_msg"] = f"✅ 賣出成功!<br>淨額 <b>${total_net_cash_native:,.0f} TWD</b><br>已自動加入「台幣帳戶餘額」!"
            
        save_data(db)
        st.rerun()

@st.dialog("✏️ 編輯 / 刪除已實現紀錄")
def edit_realized(idx):
    r = db["realized_records"][idx]
    try: sd_val = datetime.datetime.strptime(r["sell_date"], "%Y-%m-%d").date()
    except: sd_val = datetime.date.today()
    new_sd = st.date_input("賣出日期", value=sd_val)
    new_shares = st.number_input("股數", value=int(r["shares"]), min_value=1, step=1)
    new_bp = st.number_input("均進單價 (原幣別)", value=float(r["buy_price"]), min_value=0.01)
    new_sp = st.number_input("賣出單價 (原幣別)", value=float(r["sell_price"]), min_value=0.01)
    
    st.markdown("<br>", unsafe_allow_html=True)
    c1, c2 = st.columns(2)
    if c1.button("💾 儲存修改", type="primary", use_container_width=True):
        db["realized_records"][idx].update({"sell_date": str(new_sd), "shares": new_shares, "buy_price": new_bp, "sell_price": new_sp})
        save_data(db); st.rerun()
    if c2.button("🗑️ 刪除此紀錄", use_container_width=True):
        db["realized_records"].pop(idx); save_data(db); st.rerun()

# ==========================================
# ⚡ 開啟網頁 / 重新整理「自動同步股價」機制
# ==========================================
if "auto_updated" not in st.session_state:
    tickers_to_update = {r["ticker"] for r in db.get("buy_records", [])}
    if tickers_to_update:
        with st.spinner("🔄 正在為您同步最新股價..."):
            updated_any = False
            for t in tickers_to_update:
                p, n = fetch_price(t)
                if p > 0:
                    if "market_data" not in db: db["market_data"] = {}
                    if t not in db["market_data"]:
                        db["market_data"][t] = {"price": p, "name": n}
                        updated_any = True
                    elif db["market_data"][t].get("price") != p:
                        db["market_data"][t]["price"] = p
                        if n != t: db["market_data"][t]["name"] = n
                        updated_any = True
            if updated_any:
                save_data(db)
    st.session_state["auto_updated"] = True

# --- 核心計算 ---
agg = {}
for r in db["buy_records"]:
    t = r["ticker"]
    if t not in agg: agg[t] = {"shares": 0, "cost": 0}
    agg[t]["shares"] += r["shares"]; agg[t]["cost"] += r["shares"] * r["price"]

tot_exp, tot_mv, stock_unrealized, display_stocks = 0, 0, 0, []
dom_mv, for_mv_twd = 0.0, 0.0 

for t, d in agg.items():
    shares = d["shares"]
    info = db["market_data"].get(t, {"price": 0.0, "name": t})
    curr_p, name = info["price"], info["name"]
    is_foreign = not t[0].isdigit()
    
    mv_native = shares * curr_p
    mv_twd = mv_native * usd_twd_rate if is_foreign else mv_native
    
    if is_foreign: for_mv_twd += mv_twd
    else: dom_mv += mv_twd
        
    tot_mv += mv_twd
    tot_exp += (mv_twd * 2 if t.endswith("L") else mv_twd) 
    
    avg_cost_native = d["cost"] / shares
    cost_native = calc_cost_profit(t, shares, avg_cost_native, is_foreign=is_foreign)
    
    if is_foreign: sell_cost_native = float(db.get("us_stock_fee", 0.0))
    else:
        tax_rate = 0.001 if t.startswith("00") else 0.003
        sell_cost_native = (mv_native * 0.001425 * (db["fee_discount"]/10)) + (mv_native * tax_rate)
    
    un_p_native = mv_native - sell_cost_native - cost_native
    un_p_twd = un_p_native * usd_twd_rate if is_foreign else un_p_native
    
    stock_unrealized += un_p_twd
    display_stocks.append({"ticker": t, "name": name, "shares": shares, "avg_cost": avg_cost_native, "curr_p": curr_p, "mv_twd": mv_twd, "un_p_twd": un_p_twd, "ret": (un_p_native/cost_native)*100 if cost_native>0 else 0, "is_foreign": is_foreign})

stock_realized = 0.0
for r in db["realized_records"]:
    is_f = not r["ticker"][0].isdigit()
    profit_native = calc_cost_profit(r["ticker"], r["shares"], r["buy_price"], r["sell_price"], is_f)
    stock_realized += (profit_native * usd_twd_rate if is_f else profit_native)

usd_balance_twd = float(db.get("usd_balance", 0.0)) * usd_twd_rate
twd_bal = float(db.get("account_balance", 0.0))
other_ast = float(db.get("other_assets", 0.0))
futures_equity = float(db.get("futures_capital", 0.0))
pledge_amt = float(db.get("pledge_amount", 0.0))
credit_amt = float(db.get("credit_loan", 0.0))
mortgage_amt = float(db.get("mortgage_amount", 0.0))

total_assets = twd_bal + usd_balance_twd + tot_mv + other_ast + futures_equity - pledge_amt - credit_amt - mortgage_amt
total_profit = stock_unrealized + stock_realized

lev_base = twd_bal + usd_balance_twd + tot_mv + futures_equity - pledge_amt - credit_amt
lev_pct = (tot_exp / lev_base) * 100 if lev_base > 0 else 0.0
lev_str = f"{lev_pct:.1f}%"

# --- 🚀 歷史紀錄自動存檔 ---
tz_tw = timezone(timedelta(hours=8))
now_tw = datetime.datetime.now(tz_tw)
if now_tw.hour >= 15:
    t_str = now_tw.strftime('%Y-%m-%d')
    if db["history"].get(t_str, {}).get("assets") != total_assets:
        db["history"][t_str] = {"profit": total_profit, "assets": total_assets}
        save_data(db)

help_total_assets = f"""➕ 正資產 (Assets)
• 台幣帳戶餘額: ${twd_bal:,.0f}
• 美元帳戶餘額: ${usd_balance_twd:,.0f}
• 國內股票市值: ${dom_mv:,.0f}
• 國外股票市值: ${for_mv_twd:,.0f}
• 期貨權益數: ${futures_equity:,.0f}
• 其他資產: ${other_ast:,.0f}

➖ 負債 (Liabilities)
• 質押金額: ${pledge_amt:,.0f}
• 信貸金額: ${credit_amt:,.0f}
• 房貸金額: ${mortgage_amt:,.0f}"""

help_tot_exp = "所有持股市值總和\n(若持有尾碼為 L 的正2槓桿ETF,市值將自動 × 2 計算真實曝險)"
help_dom_mv = "國內台股部位即時現值總和"
help_for_mv = f"國外美股部位現值 × 即時匯率 ({usd_twd_rate})"
help_lev = "總曝險 ÷ 流動淨資產\n(排除房地產等其他資產與房貸,專注於可動用資金與股市部位)"

# ==========================================
# 🛑 攔截顯示系統提示
# ==========================================
if "success_msg" in st.session_state:
    show_success_dialog()

# --- 🚀 UI 介面 ---
st.markdown(f"#### 🗓️ {now_tw.strftime('%Y/%m/%d')}")
m1, m2 = st.columns(2)

m1.metric("總淨資產", f"${total_assets:,.0f}", help=help_total_assets)
m2.metric("總獲利", f"${total_profit:,.0f}")

st.divider()

c_a, c_set, c_up, c_out = st.columns(4)
with c_a:
    if st.button("➕", help="新增股票", use_container_width=True): add_stock()
with c_set:
    if st.button("⚙️", help="設定", use_container_width=True): show_settings()
with c_up:
    if st.button("🔄", help="強制更新報價", use_container_width=True):
        if "auto_updated" in st.session_state:
            del st.session_state["auto_updated"]
        st.rerun()
with c_out:
    # 💡 這裡改成呼叫防呆確認視窗
    if st.button("🚪", help="登出", use_container_width=True): 
        confirm_logout()

t1, t2, t3, t4, t5 = st.tabs(["💼庫存", "💰已實現", "📈獲利", "📊資產", "⚖️資金"])

with t1:
    if display_stocks:
        df_p = pd.DataFrame(display_stocks)
        
        colors_list = px.colors.qualitative.Plotly + px.colors.qualitative.Set1 + px.colors.qualitative.Pastel
        unique_tickers = df_p['ticker'].unique()
        # 💡 就在這行!補上 `ticker in` 修復語法錯誤
        color_map = {ticker: colors_list[i % len(colors_list)] for i, ticker in enumerate(unique_tickers)}
        
        c_pie, c_list = st.columns(2)
        with c_pie:
            fig = px.pie(df_p, values='mv_twd', names='ticker', hole=0.6, color='ticker', color_discrete_map=color_map)
            fig.update_layout(height=200, showlegend=False, margin=dict(t=0, b=0, l=0, r=0))
            fig.add_annotation(text=f"TWD<br>{tot_mv:,.0f}", showarrow=False, font_size=13)
            st.plotly_chart(fig, use_container_width=True)
            
        with c_list:
            st.markdown("<div style='padding-left: 5px; padding-top: 15px;'>", unsafe_allow_html=True)
            st.markdown("<div style='font-size: 14px; font-weight: bold; color: #555; margin-bottom: 8px;'>🏆 前五大持股</div>", unsafe_allow_html=True)
            top5 = df_p.nlargest(5, 'mv_twd')
            for _, row in top5.iterrows():
                pct = (row['mv_twd'] / tot_mv) * 100
                name_short = str(row['name'])[:4] 
                
                c_code = color_map.get(row['ticker'], '#888')
                dot_html = f"<span style='display:inline-block; width:10px; height:10px; background-color:{c_code}; border-radius:50%; margin-right:6px;'></span>"
                
                st.markdown(f"<div style='font-size: 12px; margin-bottom: 5px; border-bottom: 1px solid #eee; padding-bottom: 3px; display: flex; align-items: center;'>"
                            f"{dot_html}<b>{row['ticker']}</b> &nbsp;<span style='color: #888;'>{name_short}</span>"
                            f"<span style='margin-left: auto; color: #d9534f; font-weight: bold;'>{pct:.1f}%</span></div>", unsafe_allow_html=True)
            st.markdown("</div>", unsafe_allow_html=True)
        
        for s in display_stocks:
            cur_sym = "USD" if s["is_foreign"] else "TWD"
            with st.expander(f"【{s['ticker']}】{s['name']} | {cur_sym} ${s['curr_p']:,.2f}"):
                c1, c2, c3 = st.columns(3)
                c1.metric("即時庫存", f"{s['shares']:,}")
                c2.metric("現值(TWD)", f"${s['mv_twd']:,.0f}")
                c3.metric(f"均價({cur_sym})", f"${s['avg_cost']:.2f}")
                
                c4, c5, c6 = st.columns(3)
                c4.metric(f"現價({cur_sym})", f"${s['curr_p']:.2f}")
                c5.metric("損益(TWD)", f"${s['un_p_twd']:,.0f}")
                c6.metric("獲利率", f"{s['ret']:.2f}%")
                
                b1, b2 = st.columns(2)
                with b1:
                    if st.button("🔍明細", key=f"d_{s['ticker']}", use_container_width=True): show_details(s['ticker'], s['name'])
                with b2:
                    if st.button("🛒賣出", key=f"s_{s['ticker']}", use_container_width=True): sell_stock(s['ticker'], s['name'])
    else: st.info("無現貨庫存")

with t2:
    if db.get("realized_records"):
        records_with_idx = [(i, r) for i, r in enumerate(db["realized_records"])]
        for idx, r in sorted(records_with_idx, key=lambda x: x[1]["sell_date"], reverse=True):
            ticker = r["ticker"]
            shares = r["shares"]
            bp = r["buy_price"]
            sp = r["sell_price"]
            is_f = not ticker[0].isdigit()
            cur = "USD" if is_f else "TWD"
            
            disc = db.get("fee_discount", 6.0) / 10.0
            buy_cost = shares * bp
            
            if is_f:
                buy_fee = float(db.get("us_stock_fee", 0.0))
                sell_fee = float(db.get("us_stock_fee", 0.0))
                sell_tax = 0.0
            else:
                buy_fee = buy_cost * 0.001425 * disc
                sell_rev_tmp = shares * sp
                sell_fee = sell_rev_tmp * 0.001425 * disc
                tax_rate = 0.001 if ticker.startswith("00") else 0.003
                sell_tax = sell_rev_tmp * tax_rate
                
            sell_rev = shares * sp
            total_cost = buy_cost + buy_fee
            
            net_profit_native = round(sell_rev - sell_fee - sell_tax - total_cost)
            net_profit_twd = net_profit_native * usd_twd_rate if is_f else net_profit_native
            roi = (net_profit_native / total_cost) * 100 if total_cost > 0 else 0
            
            with st.expander(f"{r['sell_date']} | {ticker} | 淨利(TWD): ${net_profit_twd:,.0f}"):
                st.markdown(f"**交易:** {shares:,}股 | **均進:** ${bp:.2f} | **均出:** ${sp:.2f} ({cur})")
                c1, c2, c3 = st.columns(3)
                c1.metric("總成本", f"${round(total_cost):,}")
                c2.metric("手續費", f"${round(buy_fee + sell_fee):,}")
                c3.metric("交易稅", f"${round(sell_tax):,}")
                c4, c5, c6 = st.columns(3)
                c4.metric("賣出總額", f"${round(sell_rev):,}")
                c5.metric(f"淨損益({cur})", f"${net_profit_native:,}")
                c6.metric("報酬率", f"{roi:.2f}%")
                
                if st.button("✏️ 編輯 / 刪除此紀錄", key=f"edit_real_{idx}", use_container_width=True):
                    edit_realized(idx)
    else: st.info("無賣出紀錄")

with t3:
    if db["history"]:
        st.line_chart(pd.DataFrame([{"日期": k, "獲利": v["profit"]} for k, v in db["history"].items()]).set_index("日期"))

with t4:
    if db["history"]:
        st.line_chart(pd.DataFrame([{"日期": k, "總資產": v["assets"]} for k, v in db["history"].items()]).set_index("日期"))

with t5:
    st.markdown("#### 🛡️ 風險與資產指標")
    
    st.metric("總曝險", f"${tot_exp:,.0f}", help=help_tot_exp)
    st.metric("國內股票市值", f"${dom_mv:,.0f}", help=help_dom_mv)
    st.metric("國外股票市值", f"${for_mv_twd:,.0f}", help=help_for_mv)
    st.metric("持股水位", lev_str, help=help_lev)
    
    st.divider()
    
    st.markdown("#### ⚖️ 資金手動調整")
    c1, c2 = st.columns(2)
    nb_twd = c1.number_input("台幣帳戶餘額 (TWD)", value=int(float(db.get("account_balance", 0))))
    
    db_usd = float(db.get("usd_balance", 0.0))
    val_usd = db_usd if db_usd != 0 else None
    nb_usd = c2.number_input("美元帳戶餘額", value=val_usd, placeholder="幣別為美元", step=100.0) 
    
    nfc = c1.number_input("期貨權益數 (TWD)", value=int(float(db.get("futures_capital", 0)))) 
    np = c2.number_input("質押金額 (TWD)", value=int(float(db.get("pledge_amount", 0))))
    ncl = c1.number_input("信貸金額 (TWD)", value=int(float(db.get("credit_loan", 0))))
    nma = c2.number_input("房貸金額 (TWD)", value=int(float(db.get("mortgage_amount", 0))))
    
    db_other = float(db.get("other_assets", 0.0))
    val_other = int(db_other) if db_other != 0 else None
    no = st.number_input("其他資產 (TWD)", value=val_other, placeholder="如房地產、黃金、外幣等")
    
    if st.button("💾 確認更新資料庫", type="primary", use_container_width=True):
        db["account_balance"] = float(nb_twd)
        db["usd_balance"] = float(nb_usd) if nb_usd is not None else 0.0
        db["futures_capital"] = float(nfc)
        db["pledge_amount"] = float(np)
        db["credit_loan"] = float(ncl)
        db["mortgage_amount"] = float(nma)
        db["other_assets"] = float(no) if no is not None else 0.0
        save_data(db); st.success("已更新!"); time.sleep(1); st.rerun()