# -*- 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 streamlit as st
import streamlit.components.v1 as components
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from form_logic import (
clean_vendor_name,
FORM_TYPES,
DOC_TYPE_OPTIONS,
SIGNER_ROLES,
DISPLAY_FIELDS,
)
from auth_gate import require_login, require_authorized, render_topbar
import signer_lookup
import ai_clean
import data_source
import gates
import letter_builder
import theme
# =============================================================================
# Page Config
# =============================================================================
st.set_page_config(
page_title="PTT AUTO FORM",
page_icon="📄",
layout="wide",
initial_sidebar_state="collapsed",
)
# =============================================================================
# Health (?health=1): app booted + data source reachable. Plain text, pre-gate
# (a health probe is unauthenticated by design; reveals only byte count + time).
# Liveness alone is the built-in /_stcore/health endpoint.
# =============================================================================
if st.query_params.get("health") == "1":
_ok, _detail = data_source.check_data()
st.text(("OK " if _ok else "FAIL ") + _detail)
st.stop()
# =============================================================================
# Warm Peach CSS Theme (light cream canvas + burnt-orange accents)
# =============================================================================
st.markdown(theme.THEME_CSS, 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.
# =============================================================================
# HARD gate: phones/tablets are not supported — block before anything else (even login).
gates.require_desktop()
require_login()
# AuthZ: signing in proves who you are; ALLOWED_USERS decides who may use the app.
require_authorized()
render_topbar()
# HARD gate: must grant Local Network Access (click "Allow") before the app is usable.
gates.require_local_network()
# =============================================================================
# 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("""
PTT · PROCUREMENT TOOL
DOCUMENT GENERATOR
Auto Form
ระบบสร้างหนังสือแจ้งเข้าเริ่มงานอัตโนมัติ
""", 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, _ = data_source.load_live_data(data_source.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
# =============================================================================
# Resolve the SMP data (signer names + the TOR กำหนดส่งมอบ clause) ONCE per render.
# A single browser fetch feeds both the info card (left) and the signer field (right);
# calling fetch_signers_for_po in two places would duplicate the streamlit_js_eval key.
_po_for_smp = (st.session_state.get("last_po") or "").strip()
resolved_signers = (gates.fetch_signers_for_po(_po_for_smp)
if (_po_for_smp and st.session_state.lookup_data) else None)
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)
# Only form 1 is live; forms 2–5 are shown but locked as "coming soon".
COMING_SOON_IDS = {2, 3, 4, 5}
_form_by_label = {
f["label"] + (" 🔒 เร็ว ๆ นี้" if f["id"] in COMING_SOON_IDS else ""): f
for f in FORM_TYPES
}
form_choice = st.selectbox("ประเภทแบบฟอร์ม", list(_form_by_label.keys()), index=0,
label_visibility="collapsed",
key="form_select_widget")
selected_form = _form_by_label[form_choice]
coming_soon = selected_form["id"] in COMING_SOON_IDS
# The "coming soon" form types stay visible in the dropdown but must read as
# disabled — greyed out and unclickable. Streamlit's selectbox can't disable
# individual options, so style + lock them in the DOM (matched by the 🔒 marker
# in the label). A MutationObserver re-applies it each time the menu re-opens.
components.html("""
""", height=0)
st.markdown("", unsafe_allow_html=True)
if coming_soon:
st.info(":material/lock: แบบฟอร์มนี้กำลังจะเปิดให้ใช้งานเร็ว ๆ นี้ · Coming soon")
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",
disabled=coming_soon,
)
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) or coming_soon)
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 = data_source.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 and not coming_soon:
st.markdown('
ข้อมูลที่ถูกดึงมา
',
unsafe_allow_html=True)
vendor = clean_vendor_name(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)
st.markdown('
ข้อมูลอื่น ๆ
',
unsafe_allow_html=True)
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}")
# กำหนดส่งมอบ (การส่งมอบงาน) — pulled live from the PR's TOR via the SMP fetch
delivery = signer_lookup.pick_delivery(resolved_signers)
if delivery:
st.markdown("**กำหนดส่งมอบ:**")
st.markdown(delivery.replace("\n", " \n"))
elif resolved_signers is None:
st.caption(":material/hourglass_top: กำลังดึงกำหนดส่งมอบ…")
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"]) and not coming_soon
st.markdown("""
2
✏️
กรอกรายละเอียด เพิ่มเติม
Step 2 — Fill in additional details
""", unsafe_allow_html=True)
if not step1_done:
hint = ("🔒 แบบฟอร์มนี้ยังไม่เปิดให้ใช้งาน — เร็ว ๆ นี้" if coming_soon
else "🔒 ใส่เลข PO ในขั้นตอนที่ 1 ให้เสร็จก่อน")
st.markdown(
''
f'
{hint}
',
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"]:
# Auto-pick the default ประเภทเอกสาร from the PO's procurement type:
# งานจ้าง → แจ้งให้เริ่มเข้าทำงาน, งานซื้อ → แจ้งให้เริ่มส่งมอบสินค้า.
# Applied once per looked-up PO; the user can still change it afterwards.
if st.session_state.lookup_data and \
st.session_state.get("doc_type_auto_for") != st.session_state.last_po:
_ptype = st.session_state.lookup_data.get("procurementType")
st.session_state.doc_type_widget = letter_builder.default_doc_type(_ptype)
st.session_state.doc_type_auto_for = st.session_state.last_po
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 ในเบราว์เซอร์ (LNA ผ่านแล้วตั้งแต่หน้าแรก) — ไม่มีการกรอกเอง
signer = ""
signer_position = ""
if signer_role:
po_val = po_number.strip()
signers = None
auto = gates.signer_from_lookup(signer_role)
if not auto and po_val:
signers = resolved_signers # single fetch hoisted above the columns
if isinstance(signers, dict) and not signers.get("error"):
auto = signer_lookup.pick_signer(signers, signer_role)
if auto:
signer = auto
pos = signer_lookup.pick_position(signers, signer_role) if signers else ""
signer_position = pos
st.success(f":material/check_circle: {signer_role}: **{signer}**" + (f" — {pos}" if pos else ""))
elif signers is None and po_val:
st.info(":material/hourglass_top: กำลังดึงชื่อผู้ลงนาม…")
else:
st.warning(":material/help: ไม่พบชื่อผู้ลงนามสำหรับ PO นี้")
if st.button(":material/refresh: ลองดึงใหม่", key="signer_retry"):
st.session_state.setdefault("_signers_cache", {}).pop(po_val, None)
st.rerun()
# remember the resolved name for the stepper comparison (read at the top next render)
st.session_state["current_signer_name"] = signer
# งวดส่งมอบ — from the PR's TOR กำหนดส่งมอบ. ALWAYS show a selector so the user can pick
# which งวด this letter is for. If the TOR defines several งวด, those are the options;
# otherwise (งวดเดียว / On call) offer งวดเดียว + manual งวดที่ N — letters are issued per งวด.
delivery_raw = signer_lookup.pick_delivery(resolved_signers)
selected_nguad = None
if delivery_raw:
detected = ai_clean.parse_nguad(delivery_raw)
if len(detected) > 1:
labels = [o["label"] for o in detected] # TOR enumerates the งวด
else:
labels = ["งวดเดียว"] + [f"งวดที่ {i}" for i in range(1, 13)]
labels = labels + ["อื่นๆ (ระบุเอง)"] # let the user type a custom งวด
sel = st.selectbox("งวดส่งมอบ", labels, index=0, key="nguad_widget",
disabled=not step1_done,
help="เลือกว่าหนังสือฉบับนี้ออกสำหรับงวดใด (เช่น งาน On call / หลายงวด)")
manual = sel == "อื่นๆ (ระบุเอง)"
if manual:
sel = st.text_input("ระบุงวดส่งมอบ", placeholder="เช่น งวดที่ 5 หรือ งวดสุดท้าย",
key="nguad_manual_widget", disabled=not step1_done).strip()
num = None
if sel.startswith("งวดที่"):
try:
num = int(sel.replace("งวดที่", "").strip())
except ValueError:
num = None
selected_nguad = {"label": sel, "number": num, "manual": manual}
elif resolved_signers is None:
st.caption(":material/hourglass_top: กำลังดึงกำหนดส่งมอบจาก TOR…")
# วันที่เริ่มดำเนินการ — fills the body ("…นับถัดจากวันที่ เป็นต้นไป"). Defaults to today.
start_date_value = st.date_input("วันที่เริ่มดำเนินการ / ส่งมอบ", format="DD/MM/YYYY",
key="start_date_widget", disabled=not step1_done)
st.markdown("", unsafe_allow_html=True)
generate_clicked = st.button(":material/auto_awesome: สร้างเอกสารด้วย :violet[AI]",
type="primary",
use_container_width=True,
key="generate_btn",
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 = letter_builder.template_path_for(selected_form)
if not os.path.exists(template_path):
st.error(f"❌ ไม่พบไฟล์ template: {template_path}")
else:
status_ph = st.empty()
try:
status_ph.markdown(theme.AI_CREATE_ANIM_HTML, unsafe_allow_html=True)
output_bytes, filename, log, _used_ai = letter_builder.build_letter(
selected_form=selected_form,
doc_number=doc_number,
po_number=po_number,
doc_type=doc_type,
signer=signer,
signer_position=signer_position,
lookup_data=st.session_state.lookup_data,
start_date=start_date_value,
delivery_raw=delivery_raw,
selected_nguad=selected_nguad,
)
status_ph.empty()
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:
status_ph.empty()
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