File size: 27,749 Bytes
4584aec
 
e6660cd
ac3b103
e6660cd
ac3b103
 
e6660cd
4584aec
 
 
 
 
 
14e571e
4584aec
 
 
 
b5c887b
4584aec
 
145e4ee
4584aec
 
5ec0721
99146e1
0941280
1ea4202
84c98ae
fda2212
3c1cc18
99146e1
d15c294
4584aec
a7c7a5c
4584aec
 
5d27042
 
d939314
ac3b103
4584aec
 
a7c7a5c
21d12df
 
 
 
 
 
 
 
 
 
 
a7c7a5c
4e06d98
a7c7a5c
3c1cc18
a7c7a5c
 
e6660cd
 
 
 
d15c294
84c98ae
e6660cd
5ec0721
 
e6660cd
adf9eeb
84c98ae
e6660cd
 
4584aec
 
 
 
 
 
a7c7a5c
 
4584aec
 
 
 
 
 
a7c7a5c
4584aec
a7c7a5c
 
d939314
 
4e06d98
d939314
4e06d98
 
 
d939314
a7c7a5c
 
 
 
 
2c8ee7b
ac3b103
 
 
 
 
2c8ee7b
1ea4202
2c8ee7b
 
 
 
ac3b103
 
 
 
a7c7a5c
edc1a82
 
 
 
99146e1
 
 
edc1a82
 
f7feab1
 
 
 
 
 
 
 
edc1a82
 
 
 
 
 
 
a7c7a5c
 
d939314
 
a7c7a5c
d939314
 
4584aec
d939314
 
a7c7a5c
 
d939314
 
 
0b04419
f7feab1
d939314
 
 
0b04419
f7feab1
d939314
 
 
0b04419
d939314
 
a7c7a5c
 
 
4584aec
a7c7a5c
 
d939314
a7c7a5c
b5c887b
 
 
 
84c98ae
b5c887b
 
d939314
a7c7a5c
 
 
 
d939314
0b04419
d939314
 
 
f7feab1
 
d939314
 
 
a7c7a5c
1c8255f
 
 
 
 
 
 
edc1a82
 
1c8255f
 
a7c7a5c
2becdbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d939314
a7c7a5c
1c8255f
 
 
f7feab1
a7c7a5c
 
 
 
f7feab1
edc1a82
1c8255f
a7c7a5c
 
f7feab1
a7c7a5c
f7feab1
 
1c8255f
a7c7a5c
 
 
 
 
ac3b103
4584aec
a7c7a5c
 
1ea4202
a7c7a5c
ac3b103
 
4584aec
a7c7a5c
 
 
 
 
 
 
 
d939314
a7c7a5c
 
 
 
 
 
 
1c8255f
4b9ba9a
a7c7a5c
 
b5c887b
a7c7a5c
 
 
 
 
d939314
 
 
 
a7c7a5c
 
 
 
 
 
 
d939314
 
 
 
a7c7a5c
 
 
 
2becdbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d939314
 
 
f7feab1
e6660cd
f7feab1
 
 
 
 
d939314
 
a7c7a5c
 
 
 
f7feab1
 
1c8255f
f7feab1
d939314
0b04419
d939314
 
 
f7feab1
 
d939314
 
 
a7c7a5c
f7feab1
1c8255f
 
f7feab1
 
1c8255f
f7feab1
 
a7c7a5c
edc1a82
f7feab1
 
a7c7a5c
 
2becdbf
 
 
 
 
 
fda2212
2becdbf
a7c7a5c
 
edc1a82
f7feab1
 
a7c7a5c
 
 
145e4ee
 
 
 
 
 
adf9eeb
99146e1
b5c887b
99146e1
234b73f
 
84c98ae
234b73f
b5c887b
234b73f
 
5c120b3
 
234b73f
b5c887b
234b73f
 
adf9eeb
99146e1
adf9eeb
 
 
 
99146e1
 
a7c7a5c
83ce937
 
 
0941280
 
 
83ce937
 
 
0941280
83ce937
01672fa
83ce937
 
 
01672fa
 
 
 
83ce937
 
 
 
 
 
01672fa
83ce937
 
0941280
256df8f
 
 
 
d939314
a7c7a5c
00325cf
a7c7a5c
f7feab1
00325cf
f7feab1
a7c7a5c
 
 
 
 
145e4ee
 
a7c7a5c
 
 
 
 
 
 
fda2212
a7c7a5c
 
 
 
143187f
a7c7a5c
3c1cc18
fda2212
 
 
 
 
 
 
143187f
fda2212
 
 
143187f
 
a7c7a5c
 
 
edc1a82
 
 
 
14e571e
a7c7a5c
 
143187f
a7c7a5c
 
07a8e20
 
7061b19
 
07a8e20
7061b19
07a8e20
 
d939314
14e571e
07a8e20
 
 
 
 
 
 
 
e6660cd
 
d939314
 
e6660cd
d939314
 
e6660cd
d939314
 
 
 
a7c7a5c
d939314
a7c7a5c
 
 
 
 
 
14e571e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7c7a5c
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
# -*- 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("""
<div class="hero">
    <div class="hero-content">
        <div class="hero-badge">
            <span class="hero-badge-dot"></span>PTT · PROCUREMENT TOOL
        </div>
        <div class="hero-eyebrow">DOCUMENT GENERATOR</div>
        <div class="hero-title">Auto <span class="accent">Form</span></div>
        <p class="hero-subtitle">ระบบสร้าง<span class="hl">หนังสือแจ้งเข้าเริ่มงาน</span>อัตโนมัติ</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, _ = 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"""
<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
# =============================================================================
# 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("""
    <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)

    # 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("""
    <script>
    const doc = window.parent.document;
    const lockOptions = () => {
        doc.querySelectorAll('li[role="option"]').forEach(li => {
            if (li.textContent.includes('🔒')) {
                li.style.opacity = '0.4';
                li.style.pointerEvents = 'none';
                li.style.cursor = 'not-allowed';
                li.setAttribute('aria-disabled', 'true');
            }
        });
    };
    if (doc.__formLockObs) doc.__formLockObs.disconnect();
    const obs = new MutationObserver(lockOptions);
    obs.observe(doc.body, {childList: true, subtree: true});
    doc.__formLockObs = obs;
    lockOptions();
    </script>
    """, height=0)

    st.markdown("<div style='height: 0.5rem;'></div>", 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('<div class="section-title">ข้อมูลที่ถูกดึงมา</div>',
                    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"""
            <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)

        st.markdown('<div class="section-title">ข้อมูลอื่น ๆ</div>',
                    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("""
        <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"]) and not coming_soon

    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:
        hint = ("🔒 แบบฟอร์มนี้ยังไม่เปิดให้ใช้งาน — เร็ว ๆ นี้" if coming_soon
                else "🔒 ใส่เลข PO ในขั้นตอนที่ 1 ให้เสร็จก่อน")
        st.markdown(
            '<div class="step2-lock"></div>'
            f'<div class="step2-lock-hint">{hint}</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"]:
        # 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 ("…นับถัดจากวันที่ <date> เป็นต้นไป"). Defaults to today.
    start_date_value = st.date_input("วันที่เริ่มดำเนินการ / ส่งมอบ", format="DD/MM/YYYY",
                                     key="start_date_widget", disabled=not step1_done)

    st.markdown("<div style='height: 0.75rem;'></div>", 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("""
        <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