File size: 17,446 Bytes
4584aec
 
 
 
ea5abfd
4584aec
 
 
 
b5c887b
00325cf
256df8f
4584aec
256df8f
129e184
 
 
4584aec
00325cf
 
 
4584aec
 
 
 
 
 
129e184
4584aec
 
 
b1eb504
4584aec
 
b1eb504
4584aec
 
b1eb504
4584aec
 
b1eb504
4584aec
 
 
 
145e4ee
 
 
4584aec
 
 
 
 
b5c887b
4584aec
 
256df8f
4584aec
 
51e875d
4584aec
b1eb504
 
4584aec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0941280
 
 
 
 
 
 
 
 
 
 
00325cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256df8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4584aec
 
 
 
 
 
 
 
 
51e875d
 
 
4584aec
 
b5c887b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129e184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9c9dc4
 
 
 
 
 
 
 
 
 
129e184
 
 
 
 
 
 
 
 
4584aec
 
 
 
 
00325cf
4584aec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00325cf
 
 
 
b5c887b
4584aec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5c887b
 
 
4584aec
 
256df8f
d9c9dc4
 
 
 
 
 
4584aec
 
256df8f
 
 
 
 
129e184
 
 
 
4584aec
 
 
 
 
 
 
 
 
 
 
 
 
b1eb504
 
 
4584aec
b1eb504
 
4584aec
 
 
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
# -*- 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