# -*- coding: utf-8 -*- """ letter_builder — use-case layer: turn the user's inputs into the finished letter. build_letter() owns the whole generate flow (AI body → doc-type งวด suffix → docx render → filename) and returns plain data. No streamlit import — the UI layer (streamlit_app.py) handles widgets, error display, and session state. """ import os from io import BytesIO from datetime import datetime import ai_clean from form_logic import generate_form, clean_vendor_name, DOC_TYPE_OPTIONS TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates") def template_path_for(form): """Absolute path of the .docx template for a FORM_TYPES entry.""" return os.path.join(TEMPLATES_DIR, form["filename"]) def default_doc_type(procurement_type): """Auto-pick the default ประเภทเอกสาร from the PO's procurement type: งานจ้าง → แจ้งให้เริ่มเข้าทำงาน, งานซื้อ → แจ้งให้เริ่มส่งมอบสินค้า.""" return DOC_TYPE_OPTIONS[0] if ai_clean._is_jang(procurement_type) else DOC_TYPE_OPTIONS[1] def suffix_doc_type(doc_type_final, selected_nguad): """Append the chosen งวด to the doc type: 'แจ้งให้เริ่มเข้าทำงาน (งวดที่ 2)'.""" if selected_nguad and doc_type_final: _ng_num = selected_nguad.get("number") _ng_lab = (selected_nguad.get("label") or "").strip() if _ng_num: doc_type_final += f" (งวดที่ {_ng_num})" elif selected_nguad.get("manual") and _ng_lab: doc_type_final += f" ({_ng_lab})" return doc_type_final def build_letter(*, selected_form, doc_number, po_number, doc_type, signer, signer_position, lookup_data, start_date, delivery_raw, selected_nguad, now=None): """Generate the letter. Returns (docx_bytes, filename, log, used_ai). Raises on render failure (the UI catches and shows the error). The AI body itself never raises — ai_clean falls back to the deterministic composer. `now` exists only so tests can pin the filename timestamp.""" template_path = template_path_for(selected_form) # Clean the raw TOR delivery clause first (งวด-aware): the chosen งวด's # เงื่อนไข reaches the letter body instead of whatever งวด happens to come # first in the TOR. Never raises — deterministic fallback on any AI failure. delivery_clean, used_ai_delivery = ai_clean.clean_delivery( delivery_raw, (selected_nguad or {}).get("label")) # Guard: the AI paraphrase must not lose the "ภายใน X วัน" duration signal that # the raw TOR clause carries (LLM rewording like "ภายในระยะเวลา 120 วัน" breaks # the strict extractor). If it did, keep the raw clause for the body. if ai_clean._duration_from_tor(delivery_raw, None) and \ not ai_clean._duration_from_tor(delivery_clean, None): delivery_clean = delivery_raw # AI-generate the 2-paragraph body in the exact format (deterministic # fallback keeps it on-format if the AI Builder flow fails) ld = lookup_data or {} body_text, used_ai = ai_clean.generate_body({ "procurement_type": ld.get("procurementType"), "work": ld.get("title"), "vendor": clean_vendor_name(ld.get("VendorName")), "unit": ld.get("prCreatorUnitName"), "start_date": ai_clean.thai_date(start_date), "days": ld.get("daySLA"), "delivery_clause": delivery_clean or delivery_raw, # TOR-driven "ภายใน X วัน นับถัดจาก…" }) used_ai = used_ai or used_ai_delivery doc_type_final = doc_type if selected_form['uses_doc_type'] else "" doc_type_final = suffix_doc_type(doc_type_final, selected_nguad) 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_final, signer=signer.strip(), lookup_data=lookup_data, signer_position=signer_position.strip(), body_text=body_text, ) output_buffer.seek(0) output_bytes = output_buffer.getvalue() timestamp = (now or 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") return output_bytes, filename, log, used_ai