# -*- 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("""
""", 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("""
""", 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"""
{('✓ Step 1' if 'done' in s1 else 'Step 1')}
เลือกแบบฟอร์ม + ใส่เลข PO
{('✓ Step 2' if 'done' in s2 else 'Step 2')}
กรอกรายละเอียด เพิ่มเติม
{('✓ Step 3' if 'done' in s3 else 'Step 3')}
ดาวน์โหลด
""", 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("""
1
📋
เลือกแบบฟอร์ม + ใส่เลข PO
Step 1 — Choose form & enter PO
""", 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("", 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('
ข้อมูลที่ถูกดึงมา
',
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"""
🏢ชื่อคู่สัญญา · Vendor
{vendor}
""", unsafe_allow_html=True)
if title:
st.markdown(f"""
📝ชื่องาน · Work title
{title}
""", 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("""
ใส่เลข PO แล้วระบบจะดึงข้อมูลมาโชว์ เพื่อนำไปเติมลงในแบบฟอร์มอัตโนมัติ
""", 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("""
2
✏️
กรอกรายละเอียด เพิ่มเติม
Step 2 — Fill in additional details
""", unsafe_allow_html=True)
if not step1_done:
st.markdown(
''
'
🔒 ใส่เลข PO ในขั้นตอนที่ 1 ให้เสร็จก่อน
',
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("", 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("""
3
⬇️
ดาวน์โหลดเอกสาร
Step 3 — Download
✓สร้างเอกสารสำเร็จ!
""", 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(
"""
""",
height=0,
)
st.session_state.scroll_to_download = False