auto-form / form_logic.py
Menixis's picture
Claude Opus 4.8 (1M context)
Auto-form: เรียน vendor not bold + nudge รับทราบ box down a little
d9c9dc4
Raw History Blame Contribute Delete
17.4 kB
# -*- coding: utf-8 -*-
"""
Form Logic — pure logic for document generation (no UI dependencies)
=====================================================================
ใช้โดย streamlit_app.py (Web app ผ่าน Streamlit)
ไม่ import tkinter หรือ streamlit เลย ใช้แค่ python-docx
"""
import os
import re
import datetime
from copy import deepcopy
from docx import Document
from docx.text.paragraph import Paragraph
from docx.shared import Inches, Pt
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
_THAI_MONTHS = ["", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน",
"กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"]
# =============================================================================
# ค่าคงที่: ข้อมูลแบบฟอร์ม
# =============================================================================
FORM_TYPES = [
{"id": 1, "filename": "form1.docx",
"label": "1. หนังสือแจ้งให้เริ่มเข้าทำงาน / ส่งมอบผลิตภัณฑ์",
"uses_po": True, "uses_doc_type": True},
{"id": 2, "filename": "form2.docx",
"label": "2. หนังสือแจ้งให้กลับเข้าทำงาน (หลังแจ้งหยุดงาน)",
"uses_po": True, "uses_doc_type": False},
{"id": 3, "filename": "form3.docx",
"label": "3. หนังสือแจ้งหยุดงาน (มิใช่ความผิดของ ปตท. และคู่สัญญา)",
"uses_po": True, "uses_doc_type": False},
{"id": 4, "filename": "form4.docx",
"label": "4. หนังสือแจ้งหยุดงาน (เหตุจากความผิดของคู่สัญญา)",
"uses_po": True, "uses_doc_type": False},
{"id": 5, "filename": "form5.docx",
"label": "5. หนังสือแจ้งหยุดงาน (เหตุจากความผิดของ ปตท.)",
"uses_po": True, "uses_doc_type": False},
]
DOC_TYPE_OPTIONS = ["แจ้งให้เริ่มเข้าทำงาน", "แจ้งให้เริ่มส่งมอบสินค้า"]
# ผู้ลงนาม: เลือกบทบาทผู้ลงนาม แล้วระบบจะดึงชื่อจริงจาก API ตามบทบาทที่เลือก
SIGNER_ROLES = ["ผู้มีอำนาจอนุมัติจัดหาสินค้า", "ประธานคณะกรรมการตรวจรับ"]
# Placeholder ในแบบฟอร์มต้นฉบับ
PLACEHOLDER_DOC_NUM_F1 = "หมายเลขเอกสาร"
PLACEHOLDER_PO_F1 = "PO_No"
PLACEHOLDER_TYPE_F1 = "แจ้งให้เริ่มเข้าทำงาน / เริ่มส่งมอบสินค้า"
PLACEHOLDER_SIGNER_F1 = "ผู้มีอำนาจอนุมัติ หรือ ประธานกรรมการตรวจรับ"
PLACEHOLDER_POSITION_F1 = "ตำแหน่งผู้ลงนาม"
PLACEHOLDER_VENDOR_F1 = "Vendor"
PLACEHOLDER_WORK_F1 = "ชื่องาน"
PLACEHOLDER_BODY_F1 = "[เนื้อความ]" # the AI/deterministic 2-paragraph body
PLACEHOLDER_DOC_NUM_F2_5 = " /"
PLACEHOLDER_SIGNER_F2_5 = "( )"
PLACEHOLDER_VENDOR_F2_5 = "[ระบุชื่อคู่สัญญา]"
PLACEHOLDER_TITLE_F2_5 = "ชื่องาน" # token inserted in the "อ้างถึง (1) สัญญา…" line
PLACEHOLDER_PO_F2_5 = "PO_No" # token inserted after "เลขที่" on the same line
# Mapping จาก column ใน Excel → label ที่แสดงในผลลัพธ์
DISPLAY_FIELDS = [
("poNo", "เลข PO"),
("VendorName", "ชื่อคู่สัญญา"),
("title", "ชื่องาน"),
("prDocument", "เลขที่ PR"),
("procurementType", "ประเภทการจัดหา"),
("procurementMethod", "วิธีจัดหา"),
("prCreatorUnitName", "หน่วยงานผู้สร้าง PR"),
("budgetTH", "งบประมาณ (บาท)"),
("poCreateDate", "วันที่สร้าง PO"),
("cmsContractNo", "เลขที่สัญญา CMS"),
("daySLA", "จำนวนวัน SLA"),
]
# =============================================================================
# Utility: การแทนที่ข้อความใน docx โดยรักษารูปแบบเดิม
# =============================================================================
def _iter_paragraphs(doc):
for p in doc.paragraphs:
yield p
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
for p in cell.paragraphs:
yield p
def replace_text(doc, old_text, new_text):
"""แทนที่ข้อความทุกจุดใน document คืนค่าจำนวนครั้งที่แทนที่"""
if not old_text:
return 0
count = 0
for paragraph in _iter_paragraphs(doc):
replaced = False
for run in paragraph.runs:
if old_text in run.text:
run.text = run.text.replace(old_text, new_text)
count += 1
replaced = True
break
if replaced:
continue
if old_text in paragraph.text and paragraph.runs:
new_full = paragraph.text.replace(old_text, new_text, 1)
paragraph.runs[0].text = new_full
for r in paragraph.runs[1:]:
r.text = ""
count += 1
return count
def remove_paragraphs_containing(doc, marker):
"""Delete every paragraph whose text contains `marker`. Returns the count removed.
Used to drop an unfilled placeholder block (e.g. กำหนดส่งมอบ when there's no clause)."""
count = 0
for p in list(_iter_paragraphs(doc)):
if marker and marker in p.text:
p._element.getparent().remove(p._element)
count += 1
return count
def fill_letter_date(doc, when=None):
"""Fill the header date line 'วันที่ ___ เดือน ___ พ.ศ. ___' with `when` (default: today,
Buddhist era). Returns True if the line was found and filled."""
when = when or datetime.date.today()
new = (f"วันที่ {when.day} เดือน {_THAI_MONTHS[when.month]} "
f"พ.ศ. {when.year + 543}")
for p in _iter_paragraphs(doc):
t = p.text
if "วันที่" in t and "เดือน" in t and "พ.ศ." in t and p.runs:
p.runs[0].text = new
for r in p.runs[1:]:
r.text = ""
return True
return False
def insert_body_paragraphs(doc, placeholder, body_text):
"""Replace the single `placeholder` paragraph with one paragraph per blank-line-separated
block of `body_text`, cloning the placeholder's formatting (alignment + first-line indent).
Returns the number of paragraphs inserted."""
target = None
for p in doc.paragraphs:
if placeholder in p.text:
target = p
break
if target is None:
return 0
blocks = [b.strip() for b in re.split(r"\n\s*\n", (body_text or "").strip()) if b.strip()]
anchor = target._p
for block in blocks:
new_el = deepcopy(target._p)
anchor.addnext(new_el)
np = Paragraph(new_el, target._parent)
np.runs[0].text = " ".join(block.split()) # collapse stray newlines within a block
for r in np.runs[1:]:
r.text = ""
anchor = new_el
target._element.getparent().remove(target._element) # drop the placeholder itself
return len(blocks)
def center_text_in_parens(name, total_width=44):
inner = f" {name} ".strip()
if len(inner) >= total_width:
return f"({inner})"
pad = total_width - len(inner)
return "(" + " " * (pad // 2) + inner + " " * (pad - pad // 2) + ")"
def format_signer_line_f2_5(name):
# Centered on the page via paragraph alignment (template sets CENTER),
# so no leading-space padding here — just the parens-wrapped name.
return center_text_in_parens(name, total_width=44)
# ชื่อคู่สัญญาจาก export มาพร้อมรหัสผู้ขาย (SAP vendor code) นำหน้า เช่น
# "0010006270 บริษัท ลินเด้ (ประเทศไทย) จำกัด (มหาชน)" — ตัดรหัส (เลข ≥4 หลัก
# ตามด้วยช่องว่าง/ตัวคั่น) ที่นำหน้าออก
_VENDOR_CODE_RE = re.compile(r"^\s*\d{4,}[\s\-–—:.]+")
def clean_vendor_name(value):
"""ลบรหัสผู้ขายที่นำหน้าชื่อคู่สัญญาออก คืนค่าชื่อล้วน ๆ
(คืนค่าเดิมถ้าไม่มีรหัสนำหน้า หรือถ้าตัดแล้วจะเหลือว่าง)."""
if not value:
return ""
text = str(value).strip()
cleaned = _VENDOR_CODE_RE.sub("", text).strip()
return cleaned or text
# =============================================================================
# Keep the letter on ONE page
# =============================================================================
def _fit_letter_to_one_page(doc, body_len=0):
"""Compress the letter so it never overflows onto a 2nd page.
The template's docDefaults add 8pt space-after to every paragraph and a slightly
loose 1.08 line spacing; with a long work-title and/or body the รับทราบ box gets
pushed past the page boundary (and, having no cantSplit, splits across pages).
Clip-safe levers only (no fixed/tight line heights that would clip Thai diacritics):
• trim inter-paragraph spacing to 2pt and use single (1.0, font-relative) spacing,
• cap the bottom margin at 0.5",
• make the acknowledgement box atomic (cantSplit) so it never half-splits,
• shrink the font a step ONLY for unusually long bodies (line height is now
font-relative, so this actually reclaims space) — realistic 2-paragraph
bodies (≤ ~800 chars) stay at the full 14pt.
Verified against MS Word pagination: every realistic body length stays on one page.
"""
sec = doc.sections[0]
if sec.bottom_margin is None or sec.bottom_margin > Inches(0.5):
sec.bottom_margin = Inches(0.5)
# The box (acknowledgement) must never break across pages.
for table in doc.tables:
for row in table.rows:
trPr = row._tr.get_or_add_trPr()
if trPr.find(qn('w:cantSplit')) is None:
trPr.append(OxmlElement('w:cantSplit'))
paras = list(doc.paragraphs)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
paras += cell.paragraphs
for p in paras:
pf = p.paragraph_format
pf.space_after = Pt(2)
pf.line_spacing = 1.0
# Leave a little breathing room above the acknowledgement box (sits a bit lower).
kids = list(doc.element.body.iterchildren())
for i, ch in enumerate(kids):
if ch.tag == qn('w:tbl') and i > 0 and kids[i - 1].tag == qn('w:p'):
for p in doc.paragraphs:
if p._p is kids[i - 1]:
p.paragraph_format.space_after = Pt(14)
break
break
# Adaptive: only very long bodies need a smaller font to fit.
target = 12 if body_len > 1050 else (13 if body_len > 850 else None)
if target:
for p in paras:
for r in p.runs:
if r.font.size and r.font.size > Pt(target):
r.font.size = Pt(target)
# =============================================================================
# Logic หลัก: สร้างเอกสารตามชนิดแบบฟอร์ม
# =============================================================================
def generate_form(form_id, template_path, output_path,
doc_number, po_number, doc_type, signer,
lookup_data=None, signer_position=None, body_text=None, letter_date=None):
"""
สร้างเอกสาร Word จาก template
Args:
form_id: 1-5 (ประเภทแบบฟอร์ม)
template_path: path ของไฟล์ template .docx
output_path: path string หรือ BytesIO object สำหรับบันทึก
doc_number: หมายเลขเอกสาร (เช่น PTT-001/2568)
po_number: เลข PO
doc_type: ประเภทเอกสาร (เฉพาะ form 1)
signer: ชื่อผู้ลงนาม
lookup_data: dict ของข้อมูลจาก Excel (สำหรับ auto-fill Vendor, ชื่องาน)
Returns:
list ของข้อความ log บอกว่าแทนที่อะไรไปบ้าง
"""
if not os.path.isfile(template_path):
raise FileNotFoundError(f"ไม่พบไฟล์ template: {template_path}")
doc = Document(template_path)
log = []
# header date line 'วันที่ ___ เดือน ___ พ.ศ.' -> defaults to today
if fill_letter_date(doc, letter_date):
log.append("วันที่หนังสือ: เติมวันที่แล้ว")
vendor_name = clean_vendor_name((lookup_data or {}).get("VendorName"))
work_title = (lookup_data or {}).get("title") or ""
if form_id == 1:
n = replace_text(doc, PLACEHOLDER_DOC_NUM_F1, doc_number or "")
log.append(f"หมายเลขเอกสาร: แทนที่ {n} จุด")
n = replace_text(doc, PLACEHOLDER_PO_F1, po_number or "")
log.append(f"เลข PO: แทนที่ {n} จุด")
if doc_type:
n = replace_text(doc, PLACEHOLDER_TYPE_F1, doc_type)
log.append(f"ประเภทเอกสาร: แทนที่ {n} จุด")
n = replace_text(doc, PLACEHOLDER_SIGNER_F1, signer or "")
log.append(f"ผู้ลงนาม: แทนที่ {n} จุด")
n = replace_text(doc, PLACEHOLDER_POSITION_F1, signer_position or "")
log.append(f"ตำแหน่งผู้ลงนาม: แทนที่ {n} จุด")
if vendor_name:
n = replace_text(doc, PLACEHOLDER_VENDOR_F1, vendor_name)
log.append(f"ชื่อคู่สัญญา (เรียน): แทนที่ {n} จุด")
# the เรียน line's vendor is bold in the template — make it regular weight
for p in doc.paragraphs:
if p.text.strip().startswith("เรียน"):
for r in p.runs:
r.bold = False
break
if work_title:
n = replace_text(doc, PLACEHOLDER_WORK_F1, work_title)
log.append(f"ชื่องาน (อ้างถึง): แทนที่ {n} จุด")
# main body (เนื้อความ) — the AI/deterministic 2-paragraph text in the exact format
n = insert_body_paragraphs(doc, PLACEHOLDER_BODY_F1, body_text or "")
log.append(f"เนื้อความ: เพิ่ม {n} ย่อหน้า")
# Keep the whole letter on one page (compress spacing, atomic box, adaptive font).
_fit_letter_to_one_page(doc, body_len=len(body_text or ""))
log.append("จัดให้พอดี 1 หน้า")
else:
n = replace_text(
doc, PLACEHOLDER_DOC_NUM_F2_5,
f" {doc_number} " if doc_number else PLACEHOLDER_DOC_NUM_F2_5)
log.append(f"หมายเลขเอกสาร: แทนที่ {n} จุด")
if signer:
n = replace_text(doc, PLACEHOLDER_SIGNER_F2_5,
format_signer_line_f2_5(signer))
log.append(f"ผู้ลงนาม: แทนที่ {n} จุด")
if vendor_name:
n = replace_text(doc, PLACEHOLDER_VENDOR_F2_5, vendor_name)
log.append(f"ชื่อคู่สัญญา (Excel): แทนที่ {n} จุด")
if work_title:
n = replace_text(doc, PLACEHOLDER_TITLE_F2_5, work_title)
log.append(f"ชื่องาน (Excel): แทนที่ {n} จุด")
if po_number:
n = replace_text(doc, PLACEHOLDER_PO_F2_5, po_number)
log.append(f"เลข PO: แทนที่ {n} จุด")
doc.save(output_path)
return log