auto-form / streamlit_app.py
Menixis's picture
Claude Opus 4.8 (1M context)
signer: resolve ผู้มีอำนาจอนุมัติ / ประธานกรรมการตรวจรับ live via browser-side fetch
99146e1
Raw History Blame Contribute Delete
61 kB
# -*- coding: utf-8 -*- """ ระบบสร้างเอกสารอัตโนมัติ - Ember Dark Theme ==================================================== - Black canvas with burnt-orange ember glow accents - No sidebar — full-width main content - Compact inline data source picker - Glassmorphism charcoal cards """ import os import sys import json from io import BytesIO from datetime import datetime, date import streamlit as st import streamlit.components.v1 as components import openpyxl sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from form_logic import ( generate_form, FORM_TYPES, DOC_TYPE_OPTIONS, SIGNER_ROLES, DISPLAY_FIELDS, ) from auth_gate import require_login, render_topbar import signer_lookup # Browser-side fetch bridge (used to resolve the signer name from the SMP gateway, which # only the user's PTT-wifi browser can reach — not the HF server). Optional import so the # app still runs (with manual signer entry) if the package is absent. try: from streamlit_javascript import st_javascript except Exception: # noqa: BLE001 st_javascript = None # ============================================================================= # Helper: lookup PO ใน Excel bytes # ============================================================================= def _strip_col_wrapper(name): """'Data for Auto Form[poNo]' -> 'poNo' (header แบบ Power BI export)""" if name is None: return None s = str(name).strip() if "[" in s and s.endswith("]"): s = s.split("[", 1)[1][:-1].strip() return s def lookup_po_in_bytes(po_number, file_bytes, sheet_name=None, po_column="poNo"): wb = openpyxl.load_workbook(BytesIO(file_bytes), data_only=True, read_only=True) try: if sheet_name and sheet_name in wb.sheetnames: ws = wb[sheet_name] else: ws = wb.active rows_iter = ws.iter_rows(values_only=True) # หา header row อัตโนมัติ: รองรับไฟล์ export ตรงจาก Power BI ที่มีแถว banner/ว่าง # ด้านบน และ header แบบ 'Data for Auto Form[poNo]' — สแกน 15 แถวแรก headers = None po_col_idx = None for _ in range(15): try: raw = next(rows_iter) except StopIteration: break if not raw: continue stripped = [_strip_col_wrapper(c) for c in raw] if po_column in stripped: headers = stripped po_col_idx = stripped.index(po_column) break if headers is None: return {"__error__": f"ไม่พบคอลัมน์ '{po_column}' ในไฟล์ (sheet '{ws.title}')"}, [] available_cols = [h for h in headers if h] po_str = str(po_number).strip() for row in rows_iter: if po_col_idx >= len(row): continue cell = row[po_col_idx] if cell is None: continue if isinstance(cell, float) and cell.is_integer(): cell_str = str(int(cell)) else: cell_str = str(cell).strip() if cell_str == po_str: result = {} for i in range(min(len(headers), len(row))): if headers[i]: val = row[i] if isinstance(val, datetime): val = val.strftime("%Y-%m-%d") if not (val.hour or val.minute) \ else val.strftime("%Y-%m-%d %H:%M") elif isinstance(val, date): val = val.strftime("%Y-%m-%d") result[headers[i]] = val return result, available_cols return None, available_cols finally: wb.close() # ============================================================================= # ผู้ลงนาม: resolve a signer ROLE → the person's name. # ============================================================================= # no-reply service-account bearer (Space secret). Injected into the browser-side fetch. SMP_TOKEN = os.environ.get("SMP_TOKEN", "").strip() def fetch_signers_for_po(po): """Resolve a PO's {approver, chairman, ...} via a fetch in the USER'S browser (the HF server can't reach the PTT-internal gateway; the user's PTT-wifi browser can). Returns: a dict on success, {"error": ...} on failure, or None while still loading. Cached per-PO in session_state so the role can switch without re-fetching.""" po = (po or "").strip() if not po: return {"error": "no po"} cache = st.session_state.setdefault("_signers_cache", {}) if po in cache: return cache[po] if not st_javascript: return {"error": "browser bridge unavailable (streamlit-javascript not installed)"} if not SMP_TOKEN: return {"error": "no SMP_TOKEN configured"} js = signer_lookup.build_signers_js(po, SMP_TOKEN) res = st_javascript(js, key=f"sig::{po}") # 0/None on first run, then the JS value if isinstance(res, dict): cache[po] = res return res if isinstance(res, str) and res.strip().startswith("{"): try: d = json.loads(res) cache[po] = d return d except Exception: # noqa: BLE001 return {"error": "bad response"} return None # still resolving def fetch_signer_name(role, po=None): """Signer ROLE (+ PO) -> the person's real name, resolved live in the browser. Returns "" when not yet resolved / unavailable (the UI handles loading + manual fallback).""" if not role: return "" signers = fetch_signers_for_po(po) if not isinstance(signers, dict) or signers.get("error"): return "" return signer_lookup.pick_signer(signers, role) # ============================================================================= # Config: live data source — OneDrive "anyone with the link" (ตั้งใน Space secret DATA_URL) # ============================================================================= DATA_URL = os.environ.get("DATA_URL", "").strip() @st.cache_data(ttl=3600, show_spinner=False) def load_live_data(url): """ดึงไฟล์ Excel ล่าสุดจาก OneDrive ผ่าน anonymous link (เติม download=1) — cache 1 ชม. คืนค่า (bytes, เวลาที่ดึง)""" import requests if not url: raise RuntimeError("ยังไม่ได้ตั้งค่า DATA_URL (Space secret)") dl = url if "download=1" in url else url + ("&" if "?" in url else "?") + "download=1" r = requests.get(dl, headers={"User-Agent": "Mozilla/5.0"}, timeout=120, allow_redirects=True) r.raise_for_status() if r.content[:2] != b"PK": raise RuntimeError("ไม่ได้ไฟล์ Excel (ลิงก์อาจต้อง login หรือไม่ใช่ anonymous)") return r.content, datetime.now() # ============================================================================= # Page Config # ============================================================================= st.set_page_config( page_title="PTT AUTO FORM", page_icon="📄", layout="wide", initial_sidebar_state="collapsed", ) # ============================================================================= # Ember Dark CSS Theme (black canvas + burnt-orange accents) # ============================================================================= st.markdown(""" <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Sarabun:wght@400;500;600;700&display=swap" rel="stylesheet"> <style> /* ─── COLORS ───────────────────────────────────────────────────── Page bg : #0A0705 → #000000 (near-black, ember glow) Card surface : #161412 (charcoal panel) Field bg : #100D0B (indented input) Text primary : #F5F3F1 (near-white) Text label : #CBC4BD (warm light gray) Text muted : #928981 (warm gray) Primary action: linear-gradient #F26A3A → #E85D27 (orange→rust) Accent orange : #F26A3A Accent rust: #E85D27 Step done : #F26A3A Step active: #F2F0EE (white) Border : rgba(255, 255, 255, 0.08) ──────────────────────────────────────────────────────────────── */ /* GLOBAL */ html, body, [class*="css"], .stApp { font-family: 'Inter', 'Sarabun', -apple-system, BlinkMacSystemFont, sans-serif !important; color: #F5F3F1 !important; } /* Page background — soft warm linen with a faint coral glow */ /* Background lives on <html> with fixed attachment so it fills the viewport uniformly regardless of document scroll. (Putting it on .stApp caused a two-tone seam, because .stApp is only viewport-tall while content overflows below it.) */ html { background: radial-gradient(at 18% 8%, rgba(242, 106, 58, 0.16) 0px, transparent 55%), radial-gradient(at 85% 92%, rgba(232, 93, 39, 0.10) 0px, transparent 55%), linear-gradient(180deg, #0A0705 0%, #000000 100%) !important; background-attachment: fixed !important; /* Base colour under the fixed gradient — fills any area the fixed image doesn't paint (below the first viewport on tall pages) so there's no white band at the bottom. */ background-color: #000000 !important; } .stApp { background: transparent !important; } /* Solid black base behind everything — the html gradient uses fixed attachment and won't paint below the first viewport on tall pages, which otherwise shows as a white band at the bottom. */ body { background-color: #000000 !important; } /* Slim, theme-matched scrollbar. No scrollbar-gutter reservation — that left an empty gutter on the non-scrolling edge which painted with the native white track color (unreachable by ::-webkit-scrollbar-track), showing as a white bar. Just a normal right scrollbar with a transparent track + soft coral thumb, so there is no white bar on either side. */ html { scrollbar-color: rgba(242, 106, 58, 0.45) transparent; scrollbar-width: thin; } ::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: rgba(242, 106, 58, 0.45); border-radius: 8px; } ::-webkit-scrollbar-thumb:hover { background: rgba(242, 106, 58, 0.65); } /* Hide Streamlit chrome */ [data-testid="stToolbar"] { visibility: hidden; height: 0; position: fixed; } [data-testid="stDecoration"] { display: none; } footer { visibility: hidden; } #MainMenu { visibility: hidden; } [data-testid="stHeader"] { background: transparent !important; height: 0 !important; min-height: 0 !important; padding: 0 !important; } [data-testid="stHeader"] > div { background: transparent !important; } /* HIDE SIDEBAR ENTIRELY */ section[data-testid="stSidebar"] { display: none !important; width: 0 !important; min-width: 0 !important; max-width: 0 !important; } [data-testid="collapsedControl"], [data-testid="stSidebarCollapsedControl"], button[kind="headerNoPadding"] { display: none !important; } .block-container { padding-top: 1.5rem !important; padding-bottom: 4rem !important; max-width: 1200px !important; margin-left: auto !important; margin-right: auto !important; } /* Natural page-level scrolling + centering. Streamlit confines scrolling to an inner container (no page scrollbar), which often reads as "can't scroll". Let the document scroll instead, and keep .stApp covering the viewport so the fixed gradient background still fills the screen. */ html, body { height: auto !important; overflow-y: auto !important; } .stApp { height: auto !important; min-height: 100vh !important; overflow: visible !important; } [data-testid="stAppViewContainer"], [data-testid="stMain"] { height: auto !important; overflow: visible !important; } /* ─── ANIMATIONS ─────────────────────────────────────────────── */ @keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } @keyframes pulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(242, 106, 58, 0.4); } 50% { box-shadow: 0 0 0 7px rgba(242, 106, 58, 0); } } @keyframes blob { 0%, 100% { transform: translate(0, 0) scale(1); } 33% { transform: translate(30px, -50px) scale(1.1); } 66% { transform: translate(-20px, 20px) scale(0.9); } } /* Stepper gimmicks: breathing active circle, pop-in checkmark, growing bar */ @keyframes stepBreathe { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.08); } } @keyframes stepPop { 0% { transform: scale(0.4); opacity: 0; } 60% { transform: scale(1.18); opacity: 1; } 100% { transform: scale(1); } } @keyframes growX { from { transform: scaleX(0); } to { transform: scaleX(1); } } @keyframes barFlow { 0% { background-position: 200% 0; } 100% { background-position: 0% 0; } } /* ─── HERO ───────────────────────────────────────────────────── */ /* Dashboard hero — black panel with a warm ember glow bleeding from the top, a faint hairline grid, and a single orange dot accent. */ .hero { position: relative; background: radial-gradient(130% 150% at 50% -25%, rgba(242, 106, 58, 0.45) 0%, rgba(232, 93, 39, 0.18) 38%, transparent 72%), linear-gradient(180deg, #15110E 0%, #0B0908 100%); border: 1px solid rgba(255, 255, 255, 0.08); padding: 1.6rem 2.5rem 1.7rem; border-radius: 24px; color: #FFFFFF; margin-bottom: 2rem; overflow: hidden; box-shadow: 0 14px 44px rgba(0, 0, 0, 0.5); animation: fadeInUp 0.6s ease; } /* Single orange dot accent (echoes the reference's ⊙ mark). */ .hero::after { content: ""; position: absolute; left: 24px; bottom: 22px; width: 11px; height: 11px; border-radius: 50%; background: #F26A3A; box-shadow: 0 0 16px 3px rgba(242, 106, 58, 0.65); z-index: 3; } /* Faint hairline grid, fading out toward the bottom. */ .hero-pattern { position: absolute; inset: 0; background-image: linear-gradient(rgba(255, 255, 255, 0.045) 1px, transparent 1px), linear-gradient(90deg, rgba(255, 255, 255, 0.045) 1px, transparent 1px); background-size: 46px 46px; -webkit-mask: linear-gradient(180deg, #000 0%, transparent 88%); mask: linear-gradient(180deg, #000 0%, transparent 88%); pointer-events: none; z-index: 1; } .hero-content { position: relative; z-index: 2; text-align: left; } .hero-badge { display: inline-flex; align-items: center; gap: 0.4rem; background: rgba(255, 255, 255, 0.18); border: 1px solid rgba(255, 255, 255, 0.35); color: #FFFFFF; padding: 0.3rem 0.78rem; border-radius: 999px; font-size: 0.66rem; font-weight: 600; letter-spacing: 0.04em; margin-bottom: 2.1rem; text-transform: uppercase; } .hero .hero-title { color: #FFFFFF !important; text-align: left !important; font-size: 2.7rem !important; font-weight: 900 !important; margin: 0 0 0.85rem 0 !important; letter-spacing: -0.02em !important; line-height: 1.05 !important; text-transform: uppercase !important; text-shadow: 0 2px 10px rgba(0, 0, 0, 0.30) !important; } .hero .hero-subtitle { color: #FFFFFF !important; text-align: left !important; font-size: 1.05rem !important; font-weight: 600 !important; max-width: 600px; margin: 0 !important; line-height: 1.55; text-shadow: 0 1px 6px rgba(0, 0, 0, 0.28) !important; } /* ─── STEPS ──────────────────────────────────────────────────── */ .steps-wrapper { background: #161412; border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 16px; padding: 1.25rem 1.5rem; margin-bottom: 2rem; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25); animation: fadeInUp 0.6s ease 0.1s both; } .steps-row { display: flex; align-items: center; gap: 0; } .step { display: flex; align-items: center; gap: 0.7rem; flex: 0 0 auto; } .step-circle { height: 40px; border-radius: 999px; padding: 0 1rem; display: flex; align-items: center; justify-content: center; gap: 0.3rem; font-weight: 700; font-size: 0.95rem; white-space: nowrap; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); } .step-default .step-circle { background: rgba(255, 255, 255, 0.06); color: #928981; border: 2px solid rgba(255, 255, 255, 0.12); } .step-active .step-circle { background: #F2F0EE; color: #1A1612; box-shadow: 0 4px 16px rgba(0, 0, 0, 0.55); animation: stepBreathe 2.6s ease-in-out infinite; } .step-done .step-circle { background: linear-gradient(135deg, #F26A3A 0%, #E85D27 100%); color: white; box-shadow: 0 4px 12px rgba(242, 106, 58, 0.35); animation: stepPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) both; } .step-label { font-size: 0.85rem; font-weight: 500; color: #928981; white-space: nowrap; } .step-active .step-label { color: #F5F3F1; font-weight: 600; } .step-done .step-label { color: #F26A3A; font-weight: 600; } .step-bar { flex: 1; height: 3px; background: rgba(255, 255, 255, 0.10); margin: 0 1rem; border-radius: 999px; overflow: hidden; position: relative; } .step-bar-fill { position: absolute; inset: 0; background: linear-gradient(90deg, #F26A3A 0%, #E85D27 100%); transform-origin: left; transition: transform 0.5s ease; } .step-bar-fill.empty { transform: scaleX(0); } .step-bar-fill.full { transform: scaleX(1); background: linear-gradient(90deg, #F26A3A 0%, #E85D27 100%); animation: growX 0.6s cubic-bezier(0.65, 0, 0.35, 1) 0.1s both; } /* ─── CARDS ──────────────────────────────────────────────────── */ .card-header { display: flex; align-items: center; gap: 0.75rem; margin-bottom: 1.25rem; } .card-icon { width: 40px; height: 40px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.25rem; } .card-icon-1 { background: linear-gradient(135deg, rgba(242, 106, 58, 0.3) 0%, rgba(242, 106, 58, 0.18) 100%); } .card-icon-2 { background: linear-gradient(135deg, rgba(242, 106, 58, 0.28) 0%, rgba(242, 106, 58, 0.16) 100%); } .card-icon-3 { background: linear-gradient(135deg, rgba(232, 93, 39, 0.30) 0%, rgba(232, 93, 39, 0.16) 100%); } .card-title { font-size: 1.1rem; font-weight: 700; color: #F5F3F1; margin: 0; line-height: 1.2; } .card-subtitle { font-size: 0.8rem; color: #928981; margin: 0.15rem 0 0 0; font-weight: 500; } /* ─── STEP NUMBER BADGES (popup, straddling the card's top-left corner) ── */ .step-badge { position: absolute; top: -18px; left: -44px; width: 44px; height: 44px; border-radius: 14px; /* squircle — softer, more modern than a full circle */ display: flex; align-items: center; justify-content: center; font-size: 1.4rem; font-weight: 800; color: #FFFFFF; border: 2px solid #0A0807; /* thinner ring → less 'sticker' look */ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.32); z-index: 5; background: linear-gradient(135deg, #F26A3A 0%, #E8915E 100%); animation: stepPop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) both; } /* ─── STEP CARDS (top-level columns become distinct panels) ──── */ /* :not(...) excludes nested column rows (e.g. the PO input + button row) */ [data-testid="stColumn"]:not([data-testid="stColumn"] [data-testid="stColumn"]) { position: relative; /* anchor for the popup step badges */ background: #161412; border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 18px; padding: 1.6rem 1.7rem; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.22); } /* Locked next step: dim the whole panel when its lock marker is rendered */ [data-testid="stColumn"]:has(.step2-lock) { opacity: 0.5; transition: opacity 0.25s ease; } .step2-lock { display: none; } .step2-lock-hint { display: flex; align-items: center; gap: 0.4rem; font-size: 0.82rem; color: #928981; font-weight: 600; margin: 0 0 0.9rem 0; } /* ─── VENDOR CARDS ───────────────────────────────────────────── */ .vendor-card { background: linear-gradient(135deg, rgba(242, 106, 58, 0.14) 0%, rgba(232, 93, 39, 0.06) 100%); border: 1px solid rgba(242, 106, 58, 0.25); padding: 1rem 1.25rem; border-radius: 14px; margin: 0.6rem 0; position: relative; overflow: hidden; transition: all 0.2s ease; } .vendor-card:hover { transform: translateX(2px); box-shadow: 0 4px 16px rgba(242, 106, 58, 0.18); } .vendor-card::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 4px; background: linear-gradient(180deg, #F26A3A 0%, #E85D27 100%); } .vendor-card-label { font-size: 0.7rem; text-transform: uppercase; color: #F2B391; font-weight: 700; letter-spacing: 0.06em; margin-bottom: 0.4rem; display: flex; align-items: center; gap: 0.4rem; } .vendor-card-value { font-size: 1.05rem; color: #F5F3F1; font-weight: 600; line-height: 1.4; } /* ─── BUTTONS ────────────────────────────────────────────────── */ .stButton button[kind="primary"] { background: linear-gradient(135deg, #F26A3A 0%, #E85D27 100%) !important; border: none !important; color: #FFFFFF !important; box-shadow: 0 4px 14px rgba(242, 106, 58, 0.35) !important; font-weight: 700 !important; height: 3.25rem !important; font-size: 1.05rem !important; transition: all 0.3s ease !important; border-radius: 999px !important; } .stButton button[kind="primary"]:hover { transform: translateY(-1px); box-shadow: 0 6px 20px rgba(232, 93, 39, 0.45) !important; background: linear-gradient(135deg, #FF8A52 0%, #D2602F 100%) !important; } .stButton button[kind="secondary"] { background: rgba(242, 106, 58, 0.10) !important; border: 1.5px solid rgba(242, 106, 58, 0.35) !important; color: #F2B391 !important; font-weight: 600 !important; height: 3rem !important; border-radius: 999px !important; transition: all 0.2s ease !important; } .stButton button[kind="secondary"]:hover { background: rgba(242, 106, 58, 0.15) !important; border-color: #F26A3A !important; transform: translateY(-1px); } /* PO lookup button — match the PO input height (both pinned to 3rem via their widget keys), bottom-aligned by the column; enlarge the Material check glyph */ .st-key-po_lookup_btn button { height: 3rem !important; padding: 0 !important; } .st-key-po_lookup_btn button p, .st-key-po_lookup_btn button span, .st-key-po_lookup_btn button [data-testid="stIconMaterial"] { font-size: 1.5rem !important; } .st-key-po_input_widget [data-baseweb="input"], .st-key-po_input_widget [data-baseweb="base-input"] { height: 3rem !important; } .stDownloadButton button { background: linear-gradient(135deg, #F26A3A 0%, #E85D27 100%) !important; color: #FFFFFF !important; border: none !important; box-shadow: 0 4px 14px rgba(242, 106, 58, 0.35) !important; font-weight: 700 !important; height: 3.25rem !important; font-size: 1.05rem !important; border-radius: 999px !important; transition: all 0.3s ease !important; } .stDownloadButton button:hover { transform: translateY(-1px); box-shadow: 0 6px 20px rgba(232, 93, 39, 0.45) !important; background: linear-gradient(135deg, #FF8A52 0%, #D2602F 100%) !important; } /* Cream buttons render their label inside a stMarkdownContainer <p>, which the global markdown rule forces to light text. Re-assert purple on the label text and any Material-icon glyph so it stays readable on the cream surface. */ .stButton button[kind="primary"] [data-testid="stMarkdownContainer"] p, .stButton button[kind="primary"] [data-testid="stMarkdownContainer"] span, .stDownloadButton button [data-testid="stMarkdownContainer"] p, .stDownloadButton button [data-testid="stMarkdownContainer"] span { color: #FFFFFF !important; } /* ─── INPUTS — bulletproof dark styling ──────────────────────── */ /* All input wrappers — use SOLID dark color slightly DARKER than card bg so inputs look like "indented" surfaces, not flat boxes */ [data-testid="stTextInput"] > div > div, [data-testid="stTextInput"] > div > div > div, [data-testid="stTextInput"] [data-baseweb="input"], [data-testid="stTextInput"] [data-baseweb="base-input"], [data-testid="stTextInput"] [data-baseweb="input"] > div, [data-testid="stTextInput"] [data-baseweb="base-input"] > div, [data-baseweb="input"], [data-baseweb="base-input"], [data-baseweb="input"] > div, [data-baseweb="base-input"] > div { background-color: #100D0B !important; /* soft off-white field */ background: #100D0B !important; border: 1.5px solid rgba(242, 106, 58, 0.25) !important; border-radius: 12px !important; color: #F5F3F1 !important; box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.25) !important; /* subtle inner shadow */ } /* The actual <input> element — transparent so wrapper bg shows through */ [data-testid="stTextInput"] input, [data-baseweb="input"] input, [data-baseweb="base-input"] input, .stTextInput input, input[type="text"], input[type="number"], input[type="email"], input[type="password"] { background-color: transparent !important; background: transparent !important; color: #F5F3F1 !important; -webkit-text-fill-color: #F5F3F1 !important; font-size: 0.95rem !important; font-weight: 500 !important; /* typed text — clearly bolder */ border: none !important; caret-color: #F26A3A !important; font-style: normal !important; } /* Placeholder — clearly look like a "hint", not real text: dim muted-gray, italic, lighter weight */ [data-testid="stTextInput"] input::placeholder, [data-baseweb="input"] input::placeholder, .stTextInput input::placeholder, input::placeholder, textarea::placeholder { color: rgba(146, 137, 129, 0.65) !important; /* muted forest gray */ font-style: italic !important; font-weight: 400 !important; opacity: 1 !important; -webkit-text-fill-color: rgba(146, 137, 129, 0.65) !important; } /* Webkit autofill — prevent yellow bg */ input:-webkit-autofill, input:-webkit-autofill:hover, input:-webkit-autofill:focus { -webkit-text-fill-color: #F5F3F1 !important; -webkit-box-shadow: 0 0 0 1000px #100D0B inset !important; box-shadow: 0 0 0 1000px #100D0B inset !important; background: #100D0B !important; } /* Focus state — emerald glow on wrapper + subtle lift */ [data-testid="stTextInput"] > div > div:focus-within, [data-baseweb="input"]:focus-within, [data-baseweb="base-input"]:focus-within { border-color: #F26A3A !important; box-shadow: 0 0 0 4px rgba(242, 106, 58, 0.25), inset 0 1px 2px rgba(0, 0, 0, 0.04) !important; background-color: #1F1A16 !important; background: #1F1A16 !important; } /* Selectbox — same treatment, deep nesting */ [data-testid="stSelectbox"] > div > div, [data-testid="stSelectbox"] > div > div > div, [data-testid="stSelectbox"] [data-baseweb="select"], [data-testid="stSelectbox"] [data-baseweb="select"] > div, [data-baseweb="select"], [data-baseweb="select"] > div, [data-baseweb="select"] > div > div { background-color: #100D0B !important; background: #100D0B !important; border: 1.5px solid rgba(242, 106, 58, 0.25) !important; border-radius: 12px !important; color: #F5F3F1 !important; } [data-baseweb="select"] *, [data-baseweb="select"] span, [data-baseweb="select"] div { color: #F5F3F1 !important; } [data-testid="stSelectbox"] svg, [data-baseweb="select"] svg { fill: #F2B391 !important; } /* Selectbox dropdown popover (portaled outside main DOM — needs high specificity). Dark surface on the whole menu + every wrapper, but the rounded frame + shadow live on the listbox ONLY — so individual options stay flat. (Previously the descendant catch-all applied border/radius/shadow to every option, giving the "messy" nested-box look.) */ html body [data-baseweb="popover"], html body [data-baseweb="popover"] > div, html body [data-baseweb="popover"] > div > div, html body [data-baseweb="popover"] [data-baseweb="menu"], html body div[data-baseweb="popover"] *, [role="listbox"], ul[role="listbox"], div[role="listbox"] { background: #1F1A16 !important; background-color: #1F1A16 !important; color: #F5F3F1 !important; border: none !important; border-radius: 0 !important; box-shadow: none !important; } /* The single rounded frame: the listbox container only */ html body [data-baseweb="popover"] [role="listbox"], [role="listbox"] { border: 1px solid rgba(242, 106, 58, 0.3) !important; border-radius: 12px !important; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35) !important; } /* Each option in the dropdown — force dark bg + light text */ html body [data-baseweb="popover"] li, html body [data-baseweb="menu"] li, html body [role="option"], html body ul[role="listbox"] > li, li[role="option"] { background: #1F1A16 !important; background-color: #1F1A16 !important; color: #F5F3F1 !important; -webkit-text-fill-color: #F5F3F1 !important; padding: 0.55rem 0.85rem !important; } /* Force inner content of option to inherit light color */ html body [data-baseweb="popover"] li *, html body [role="option"] *, li[role="option"] *, li[role="option"] div, li[role="option"] span { color: #F5F3F1 !important; -webkit-text-fill-color: #F5F3F1 !important; background: transparent !important; background-color: transparent !important; } /* Hover state */ html body [data-baseweb="popover"] li:hover, html body [role="option"]:hover, li[role="option"]:hover { background: rgba(242, 106, 58, 0.22) !important; background-color: rgba(242, 106, 58, 0.22) !important; color: #F2B391 !important; } html body [data-baseweb="popover"] li:hover *, html body [role="option"]:hover *, li[role="option"]:hover * { color: #F2B391 !important; -webkit-text-fill-color: #F2B391 !important; } /* Selected option */ html body [role="option"][aria-selected="true"], li[role="option"][aria-selected="true"] { background: rgba(242, 106, 58, 0.18) !important; background-color: rgba(242, 106, 58, 0.18) !important; color: #F2B391 !important; } /* Scrollbar inside dropdown */ [data-baseweb="popover"] ul::-webkit-scrollbar, [role="listbox"]::-webkit-scrollbar { width: 8px; background: transparent; } [data-baseweb="popover"] ul::-webkit-scrollbar-thumb, [role="listbox"]::-webkit-scrollbar-thumb { background: rgba(242, 106, 58, 0.3); border-radius: 4px; } /* Textarea — same treatment */ .stTextArea textarea, [data-baseweb="textarea"] textarea, [data-testid="stTextArea"] textarea { background-color: #100D0B !important; background: #100D0B !important; color: #F5F3F1 !important; border: 1.5px solid rgba(242, 106, 58, 0.25) !important; border-radius: 12px !important; -webkit-text-fill-color: #F5F3F1 !important; } /* Radio buttons — text color and indicator */ .stRadio label, .stRadio [data-baseweb="radio"] label, .stRadio > div > div { color: #F5F3F1 !important; } .stRadio [data-baseweb="radio"] div[role="radio"] { background-color: rgba(255, 255, 255, 0.05) !important; border-color: rgba(242, 106, 58, 0.4) !important; } .stRadio [data-baseweb="radio"] div[role="radio"][aria-checked="true"] { background-color: #F26A3A !important; border-color: #F26A3A !important; } /* File uploader */ [data-testid="stFileUploader"] section, [data-testid="stFileUploader"] > div { background: rgba(255, 255, 255, 0.04) !important; border: 2px dashed rgba(242, 106, 58, 0.3) !important; border-radius: 14px !important; color: #F5F3F1 !important; } [data-testid="stFileUploader"] button { background: rgba(242, 106, 58, 0.15) !important; color: #F2B391 !important; border: 1px solid rgba(242, 106, 58, 0.3) !important; } [data-testid="stFileUploader"] small, [data-testid="stFileUploader"] span { color: #CBC4BD !important; } /* Labels above inputs */ .stTextInput label, .stTextInput label p, .stSelectbox label, .stSelectbox label p, .stRadio label > div:first-child, .stFileUploader label { font-weight: 600 !important; color: #CBC4BD !important; font-size: 0.85rem !important; } /* ─── ALERTS ─────────────────────────────────────────────────── */ .stAlert { border-radius: 14px !important; border: none !important; backdrop-filter: blur(10px); } [data-testid="stNotificationContentSuccess"] { background: rgba(242, 106, 58, 0.15) !important; color: #F26A3A !important; } [data-testid="stNotificationContentInfo"] { background: rgba(242, 106, 58, 0.18) !important; color: #F2B391 !important; } /* Warning alert. Streamlit 1.57 paints the colored box on stAlertContainer (the old stNotificationContentWarning testid no longer exists); scope to warnings only via :has() so success/info/error keep their own colors. */ [data-testid="stAlertContainer"]:has([data-testid="stAlertContentWarning"]) { background: rgba(252, 211, 77, 0.12) !important; border: 1px solid rgba(252, 211, 77, 0.35) !important; border-left: 4px solid #FCD34D !important; } [data-testid="stAlertContentWarning"], [data-testid="stAlertContentWarning"] * { color: #FCD34D !important; } [data-testid="stAlertContainer"]:has([data-testid="stAlertContentWarning"]) svg { fill: #FCD34D !important; } [data-testid="stNotificationContentError"] { background: rgba(239, 68, 68, 0.18) !important; color: #FF8A80 !important; } /* ─── EXPANDERS ──────────────────────────────────────────────── */ .streamlit-expanderHeader, [data-testid="stExpander"] summary { background: rgba(255, 255, 255, 0.04) !important; border-radius: 12px !important; color: #CBC4BD !important; font-weight: 600 !important; border: 1px solid rgba(242, 106, 58, 0.12) !important; } [data-testid="stExpander"] { background: transparent !important; border: none !important; } [data-testid="stExpander"] details { background: transparent !important; border: none !important; } [data-testid="stExpander"] [data-testid="stExpanderDetails"] { background: rgba(255, 255, 255, 0.03) !important; border: 1px solid rgba(242, 106, 58, 0.1) !important; border-radius: 12px !important; padding: 1rem !important; margin-top: 0.5rem !important; } /* ─── SECTION TITLE ──────────────────────────────────────────── */ .section-title { font-size: 0.95rem; font-weight: 700; color: #F5F3F1; margin: 1.25rem 0 0.75rem 0; display: flex; align-items: center; gap: 0.5rem; } .section-title::before { content: ""; width: 4px; height: 18px; background: linear-gradient(180deg, #F26A3A 0%, #E85D27 100%); border-radius: 2px; } /* ─── EMPTY STATE ────────────────────────────────────────────── */ .empty-state { text-align: center; padding: 2rem 1rem; background: rgba(255, 255, 255, 0.03); border-radius: 14px; border: 2px dashed rgba(242, 106, 58, 0.2); margin: 1rem 0; } .empty-state-icon { margin-bottom: 0.75rem; opacity: 0.7; line-height: 0; } .empty-state-text { color: #928981; font-size: 0.9rem; margin: 0; } /* ─── DIVIDER ─────────────────────────────────────────────────── */ hr { border: none !important; height: 1px !important; background: linear-gradient(90deg, transparent 0%, rgba(242, 106, 58, 0.25) 50%, transparent 100%) !important; margin: 1rem 0 !important; } /* Captions */ .caption, .stCaption, [data-testid="stCaptionContainer"] { color: #928981 !important; } /* Markdown content (general text) */ .stMarkdown, .stMarkdown p, [data-testid="stMarkdownContainer"] { color: #F5F3F1 !important; } .stMarkdown strong { color: #F2B391 !important; } .stMarkdown code { background: rgba(242, 106, 58, 0.16) !important; color: #F2B391 !important; padding: 0.15rem 0.45rem !important; border-radius: 6px !important; } /* Spinner */ .stSpinner > div { border-top-color: #F26A3A !important; } </style> """, unsafe_allow_html=True) # ============================================================================= # Authentication gate — must sign in with PTT (Entra ID) before using the app. # Renders the themed login screen and st.stop()s when not authenticated. # ============================================================================= require_login() render_topbar() # ============================================================================= # Session State # ============================================================================= for key, default in [ ("lookup_data", None), ("last_po", ""), ("generated_file", None), ("generated_filename", None), ]: if key not in st.session_state: st.session_state[key] = default # ============================================================================= # Hero Section # ============================================================================= st.markdown(""" <div class="hero"> <div class="hero-pattern"></div> <div class="hero-content"> <div class="hero-badge"> PTT documents generator </div> <div class="hero-title">Auto Form</div> <p class="hero-subtitle"> สร้างหนังสือแจ้งเข้าทำงาน/แจ้งส่งสินค้า จากแบบฟอร์มมาตรฐาน แบบอัตโนมัติ </p> </div> </div> """, unsafe_allow_html=True) # ============================================================================= # Load PO data (live source, with sample fallback) # ============================================================================= sample_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sample_po_data.xlsx') excel_bytes = None try: excel_bytes, _ = load_live_data(DATA_URL) except Exception: if os.path.exists(sample_path): with open(sample_path, 'rb') as f: excel_bytes = f.read() # ============================================================================= # Step Indicator (reacts to current form state) # ============================================================================= has_file = bool(st.session_state.generated_file) cur_po = st.session_state.get("po_input_widget", "") or "" cur_doc = st.session_state.get("doc_number_widget", "") or "" # resolved signer name from the previous render (the live fetch happens in Step 2 below); # used only for the stepper's "already generated?" comparison. cur_signer = st.session_state.get("current_signer_name", "") cur_form = st.session_state.get("form_select_widget", FORM_TYPES[0]["label"]) # Going back to edit Step 1 must regress the timeline: if the PO field no longer # matches the PO that was looked up (cleared or changed), drop the stale lookup so # has_lookup → False and the stepper returns to the real current step. if st.session_state.lookup_data and cur_po.strip() != st.session_state.get("last_po", ""): st.session_state.lookup_data = None has_lookup = bool(st.session_state.lookup_data) inputs_match_snapshot = ( cur_po.strip() == st.session_state.get("last_gen_po", "") and cur_doc.strip() == st.session_state.get("last_gen_doc", "") and cur_signer.strip() == st.session_state.get("last_gen_signer", "") and cur_form == st.session_state.get("last_gen_form", "") ) has_generated = has_file and inputs_match_snapshot if has_generated: s1, s2, s3 = "step-done", "step-done", "step-done" bar1, bar2 = "full", "full" elif has_lookup: s1, s2, s3 = "step-done", "step-active", "step-default" bar1, bar2 = "full", "empty" else: s1, s2, s3 = "step-active", "step-default", "step-default" bar1, bar2 = "empty", "empty" st.markdown(f""" <div class="steps-wrapper"> <div class="steps-row"> <div class="step {s1}"> <div class="step-circle">{('✓ Step 1' if 'done' in s1 else 'Step 1')}</div> <span class="step-label">เลือกแบบฟอร์ม + ใส่เลข PO</span> </div> <div class="step-bar"><div class="step-bar-fill {bar1}"></div></div> <div class="step {s2}"> <div class="step-circle">{('✓ Step 2' if 'done' in s2 else 'Step 2')}</div> <span class="step-label">กรอกรายละเอียด เพิ่มเติม</span> </div> <div class="step-bar"><div class="step-bar-fill {bar2}"></div></div> <div class="step {s3}"> <div class="step-circle">{('✓ Step 3' if 'done' in s3 else 'Step 3')}</div> <span class="step-label">ดาวน์โหลด</span> </div> </div> </div> """, unsafe_allow_html=True) # ============================================================================= # Two-Column Layout # ============================================================================= left_col, right_col = st.columns([1.05, 1], gap="large") # === LEFT: Form selection + PO lookup === with left_col: st.markdown(""" <div class="step-badge step-badge-1">1</div> <div class="card-header"> <div class="card-icon card-icon-1">📋</div> <div> <h3 class="card-title">เลือกแบบฟอร์ม + ใส่เลข PO</h3> <p class="card-subtitle">Step 1 — Choose form & enter PO</p> </div> </div> """, unsafe_allow_html=True) form_labels = [f["label"] for f in FORM_TYPES] form_choice = st.selectbox("ประเภทแบบฟอร์ม", form_labels, index=0, label_visibility="collapsed", key="form_select_widget") selected_form = next(f for f in FORM_TYPES if f["label"] == form_choice) st.markdown("<div style='height: 0.5rem;'></div>", unsafe_allow_html=True) col_po, col_btn = st.columns([5, 1], vertical_alignment="bottom") with col_po: po_number = st.text_input( "เลข PO" + (" *" if selected_form["uses_po"] else ""), value=st.session_state.last_po, placeholder="เช่น 4141000xxx", key="po_input_widget", ) with col_btn: fetch_clicked = st.button(":material/check_circle:", use_container_width=True, type="primary", key="po_lookup_btn", disabled=(excel_bytes is None)) if fetch_clicked: if not po_number.strip(): st.warning("⚠ กรุณากรอกเลข PO ก่อน") elif not excel_bytes: st.error("ไม่มีไฟล์ Excel") else: with st.spinner("กำลังค้นหา..."): try: result, available_cols = lookup_po_in_bytes( po_number.strip(), excel_bytes, sheet_name=st.session_state.get("adv_sheet_name", "") or None, po_column=st.session_state.get("adv_po_column", "poNo").strip() or "poNo", ) if isinstance(result, dict) and "__error__" in result: st.error(result["__error__"]) if available_cols: st.caption(f"คอลัมน์ที่พบ: {', '.join(available_cols[:10])}") st.session_state.lookup_data = None elif result: st.session_state.lookup_data = result st.session_state.last_po = po_number.strip() st.session_state.generated_file = None st.rerun() else: st.warning(f"⚠ ไม่พบ PO: {po_number}") st.session_state.lookup_data = None except Exception as e: st.error(f"❌ ผิดพลาด: {e}") if st.session_state.lookup_data: st.markdown('<div class="section-title">ข้อมูลที่ถูกดึงมา</div>', unsafe_allow_html=True) vendor = st.session_state.lookup_data.get('VendorName') title = st.session_state.lookup_data.get('title') if vendor: st.markdown(f""" <div class="vendor-card"> <div class="vendor-card-label"> <span>🏢</span> <span>ชื่อคู่สัญญา · Vendor</span> </div> <div class="vendor-card-value">{vendor}</div> </div> """, unsafe_allow_html=True) if title: st.markdown(f""" <div class="vendor-card"> <div class="vendor-card-label"> <span>📝</span> <span>ชื่องาน · Work title</span> </div> <div class="vendor-card-value">{title}</div> </div> """, unsafe_allow_html=True) with st.expander("📋 ดูข้อมูลอื่น ๆ"): for col, label in DISPLAY_FIELDS: if col in ("VendorName", "title"): continue val = st.session_state.lookup_data.get(col) if val not in (None, ""): st.markdown(f"**{label}:** {val}") else: st.markdown(""" <div class="empty-state"> <div class="empty-state-icon"> <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="#F26A3A" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"> <circle cx="11" cy="11" r="7"></circle> <line x1="21" y1="21" x2="16.65" y2="16.65"></line> </svg> </div> <p class="empty-state-text">ใส่เลข PO แล้วระบบจะดึงข้อมูลมาโชว์<br>เพื่อนำไปเติมลงในแบบฟอร์มอัตโนมัติ</p> </div> """, unsafe_allow_html=True) # === RIGHT: Document details + Generate === with right_col: # Step 2 unlocks once Step 1 is complete. Forms that don't use a PO have no # lookup step, so Step 2 is available for them immediately. step1_done = has_lookup or not selected_form["uses_po"] st.markdown(""" <div class="step-badge step-badge-2">2</div> <div class="card-header"> <div class="card-icon card-icon-2">✏️</div> <div> <h3 class="card-title">กรอกรายละเอียด เพิ่มเติม</h3> <p class="card-subtitle">Step 2 — Fill in additional details</p> </div> </div> """, unsafe_allow_html=True) if not step1_done: st.markdown( '<div class="step2-lock"></div>' '<div class="step2-lock-hint">🔒 ใส่เลข PO ในขั้นตอนที่ 1 ให้เสร็จก่อน</div>', unsafe_allow_html=True) doc_number = st.text_input("หมายเลขเอกสาร *", placeholder="เช่น PTT-001/2568", key="doc_number_widget", disabled=not step1_done) if selected_form["uses_doc_type"]: doc_type = st.radio("ประเภทเอกสาร", DOC_TYPE_OPTIONS, horizontal=True, key="doc_type_widget", disabled=not step1_done) else: doc_type = "" signer_role = st.selectbox("ผู้ลงนาม *", SIGNER_ROLES, index=None, placeholder="เลือกผู้มีอำนาจลงนาม", key="signer_role_widget", disabled=not step1_done) # เลือกบทบาทแล้วดึงชื่อจริงสด ๆ จากระบบ SMP ผ่านเบราว์เซอร์ของผู้ใช้ (ซึ่งอยู่บนเครือข่าย PTT) signer = "" if signer_role: po_val = po_number.strip() signers = fetch_signers_for_po(po_val) if po_val else {"error": "no po"} if signers is None: st.info(":material/hourglass_top: กำลังดึงชื่อผู้ลงนามจากระบบ…") elif signers.get("error"): st.warning(":material/wifi_off: ดึงชื่ออัตโนมัติไม่ได้ " "(ต้องอยู่ในเครือข่าย PTT) — กรอกชื่อผู้ลงนามเอง") signer = st.text_input("ชื่อผู้ลงนาม", key="signer_manual_widget").strip() else: signer = signer_lookup.pick_signer(signers, signer_role) if signer: pos = signer_lookup.pick_position(signers, signer_role) st.success(f":material/check_circle: {signer_role}: **{signer}**" + (f" — {pos}" if pos else "")) else: st.warning(":material/help: ไม่พบชื่อสำหรับบทบาทนี้ใน PO นี้ — กรอกเอง") signer = st.text_input("ชื่อผู้ลงนาม", key="signer_manual_widget").strip() # remember the resolved name for the stepper comparison (read at the top next render) st.session_state["current_signer_name"] = signer st.markdown("<div style='height: 0.75rem;'></div>", unsafe_allow_html=True) generate_clicked = st.button(":material/auto_awesome: สร้างเอกสาร", type="primary", use_container_width=True, disabled=not step1_done) if generate_clicked: errors = [] if not doc_number.strip(): errors.append("กรุณากรอกหมายเลขเอกสาร") if not signer_role: errors.append("กรุณาเลือกผู้ลงนาม") if selected_form["uses_po"] and not po_number.strip(): errors.append("กรุณากรอกเลข PO") if errors: for err in errors: st.error(f"⚠ {err}") else: template_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'templates', selected_form['filename'] ) if not os.path.exists(template_path): st.error(f"❌ ไม่พบไฟล์ template: {template_path}") else: try: with st.spinner("กำลังสร้างเอกสาร..."): output_buffer = BytesIO() log = generate_form( form_id=selected_form['id'], template_path=template_path, output_path=output_buffer, doc_number=doc_number.strip(), po_number=po_number.strip(), doc_type=doc_type if selected_form['uses_doc_type'] else "", signer=signer.strip(), lookup_data=st.session_state.lookup_data, ) output_buffer.seek(0) output_bytes = output_buffer.getvalue() timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") safe_num = doc_number.replace('/', '-').replace('\\', '-').strip() filename = (f"form{selected_form['id']}_{safe_num}_{timestamp}.docx" if safe_num else f"form{selected_form['id']}_{timestamp}.docx") st.session_state.generated_file = output_bytes st.session_state.generated_filename = filename st.session_state.last_gen_po = po_number.strip() st.session_state.last_gen_doc = doc_number.strip() st.session_state.last_gen_signer = signer.strip() st.session_state.last_gen_form = selected_form["label"] st.session_state.scroll_to_download = True st.rerun() except Exception as e: st.error(f"❌ ไม่สามารถสร้างเอกสารได้: {e}") # ============================================================================= # Step 3 — Download (its own box, full-width below Steps 1 & 2) # Shown only while the current inputs still match the generated document; editing # a previous step makes has_generated False, so this box disappears. # ============================================================================= if has_generated: step3_box = st.columns([1])[0] with step3_box: st.markdown(""" <div id="download-anchor" style="position:absolute; top:0; left:0; scroll-margin-top:90px;"></div> <div class="step-badge">3</div> <div class="card-header"> <div class="card-icon card-icon-3">⬇️</div> <div> <h3 class="card-title">ดาวน์โหลดเอกสาร</h3> <p class="card-subtitle">Step 3 — Download</p> </div> </div> <div style="background: linear-gradient(135deg, rgba(242, 106, 58, 0.16) 0%, rgba(242, 106, 58, 0.10) 100%); border: 1px solid rgba(242, 106, 58, 0.4); padding: 0.85rem 1rem; border-radius: 14px; margin-bottom: 0.75rem;"> <div style="display: flex; align-items: center; gap: 0.5rem;"> <span style="background: linear-gradient(135deg, #F26A3A, #E85D27); color: white; width: 24px; height: 24px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; font-size: 0.85rem;">✓</span> <span style="font-weight: 600; color: #F26A3A;">สร้างเอกสารสำเร็จ!</span> </div> </div> """, unsafe_allow_html=True) st.download_button( label="⬇ ดาวน์โหลดเอกสาร", data=st.session_state.generated_file, file_name=st.session_state.generated_filename, mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document", use_container_width=True, ) # One-shot: after pressing "สร้างเอกสาร", smooth-scroll the page down to the # download box. Runs only on the rerun that follows generation, then clears. if st.session_state.get("scroll_to_download"): components.html( """ <script> const doc = window.parent.document; let tries = 0; const timer = setInterval(() => { const el = doc.getElementById('download-anchor'); if (el) { el.scrollIntoView({behavior: 'smooth', block: 'start'}); clearInterval(timer); } if (++tries > 20) clearInterval(timer); }, 80); </script> """, height=0, ) st.session_state.scroll_to_download = False
# -*- coding: utf-8 -*-
"""
ระบบสร้างเอกสารอัตโนมัติ - Ember Dark Theme
====================================================
- Black canvas with burnt-orange ember glow accents
- No sidebar — full-width main content
- Compact inline data source picker
- Glassmorphism charcoal cards
"""
import os
import sys
import json
from io import BytesIO
from datetime import datetime, date
import streamlit as st
import streamlit.components.v1 as components
import openpyxl
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from form_logic import (
generate_form,
FORM_TYPES,
DOC_TYPE_OPTIONS,
SIGNER_ROLES,
DISPLAY_FIELDS,
)
from auth_gate import require_login, render_topbar
import signer_lookup
# Browser-side fetch bridge (used to resolve the signer name from the SMP gateway, which
# only the user's PTT-wifi browser can reach — not the HF server). Optional import so the
# app still runs (with manual signer entry) if the package is absent.
try:
from streamlit_javascript import st_javascript
except Exception: # noqa: BLE001
st_javascript = None
# =============================================================================
# Helper: lookup PO ใน Excel bytes
# =============================================================================
def _strip_col_wrapper(name):
"""'Data for Auto Form[poNo]' -> 'poNo' (header แบบ Power BI export)"""
if name is None:
return None
s = str(name).strip()
if "[" in s and s.endswith("]"):
s = s.split("[", 1)[1][:-1].strip()
return s
def lookup_po_in_bytes(po_number, file_bytes, sheet_name=None, po_column="poNo"):
wb = openpyxl.load_workbook(BytesIO(file_bytes), data_only=True, read_only=True)
try:
if sheet_name and sheet_name in wb.sheetnames:
ws = wb[sheet_name]
else:
ws = wb.active
rows_iter = ws.iter_rows(values_only=True)
# หา header row อัตโนมัติ: รองรับไฟล์ export ตรงจาก Power BI ที่มีแถว banner/ว่าง
# ด้านบน และ header แบบ 'Data for Auto Form[poNo]' — สแกน 15 แถวแรก
headers = None
po_col_idx = None
for _ in range(15):
try:
raw = next(rows_iter)
except StopIteration:
break
if not raw:
continue
stripped = [_strip_col_wrapper(c) for c in raw]
if po_column in stripped:
headers = stripped
po_col_idx = stripped.index(po_column)
break
if headers is None:
return {"__error__": f"ไม่พบคอลัมน์ '{po_column}' ในไฟล์ (sheet '{ws.title}')"}, []
available_cols = [h for h in headers if h]
po_str = str(po_number).strip()
for row in rows_iter:
if po_col_idx >= len(row):
continue
cell = row[po_col_idx]
if cell is None:
continue
if isinstance(cell, float) and cell.is_integer():
cell_str = str(int(cell))
else:
cell_str = str(cell).strip()
if cell_str == po_str:
result = {}
for i in range(min(len(headers), len(row))):