File size: 7,137 Bytes
f50726e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
903bb5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9e493a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""letter_builder — the generate use-case, end-to-end with the real form1 template."""
from datetime import date, datetime
from io import BytesIO

from docx import Document

import letter_builder
from form_logic import DOC_TYPE_OPTIONS, FORM_TYPES

LOOKUP = {
    "poNo": "4500987654",
    "VendorName": "0010001234 บริษัท ทดสอบ จำกัด",
    "title": "งานจ้างเหมาบำรุงรักษาระบบท่อ",
    "procurementType": "งานจ้างบริการ",
    "prCreatorUnitName": "ส่วนบำรุงรักษาระบบท่อ",
    "daySLA": 90,
}


def test_default_doc_type():
    assert letter_builder.default_doc_type("งานจ้างบริการ") == DOC_TYPE_OPTIONS[0]
    assert letter_builder.default_doc_type("งานซื้อ") == DOC_TYPE_OPTIONS[1]
    assert letter_builder.default_doc_type(None) == DOC_TYPE_OPTIONS[1]


def test_suffix_doc_type():
    ng_num = {"label": "งวดที่ 2", "number": 2, "manual": False}
    ng_manual = {"label": "งวดสุดท้าย", "number": None, "manual": True}
    assert letter_builder.suffix_doc_type("แจ้งให้เริ่มเข้าทำงาน", ng_num) == \
        "แจ้งให้เริ่มเข้าทำงาน (งวดที่ 2)"
    assert letter_builder.suffix_doc_type("แจ้งให้เริ่มเข้าทำงาน", ng_manual) == \
        "แจ้งให้เริ่มเข้าทำงาน (งวดสุดท้าย)"
    assert letter_builder.suffix_doc_type("แจ้งให้เริ่มเข้าทำงาน", None) == \
        "แจ้งให้เริ่มเข้าทำงาน"
    # forms without a doc type stay empty — no งวด suffix appears from nowhere
    assert letter_builder.suffix_doc_type("", ng_num) == ""


def test_build_letter_form1():
    docx_bytes, filename, log, used_ai = letter_builder.build_letter(
        selected_form=FORM_TYPES[0],
        doc_number="PTT-001/2568",
        po_number="4500987654",
        doc_type=DOC_TYPE_OPTIONS[0],
        signer="นายทดสอบ ระบบดี",
        signer_position="ผู้จัดการฝ่ายทดสอบ",
        lookup_data=LOOKUP,
        start_date=date(2026, 7, 20),
        delivery_raw="ส่งมอบงานภายใน 90 (เก้าสิบ) วัน นับถัดจากวันที่ได้รับหนังสือแจ้ง",
        selected_nguad={"label": "งวดที่ 2", "number": 2, "manual": False},
        now=datetime(2026, 7, 16, 12, 0, 0),
    )
    assert used_ai is False                      # AI_BACKEND=off
    assert docx_bytes[:2] == b"PK"
    assert filename == "form1_PTT-001-2568_20260716_120000.docx"
    assert log                                   # the render log is populated

    doc = Document(BytesIO(docx_bytes))
    all_text = "\n".join(p.text for p in doc.paragraphs)
    assert "[เนื้อความ]" not in all_text         # body placeholder replaced
    assert "ตามที่" in all_text and "จึงขอแจ้งให้" in all_text
    assert "บริษัท ทดสอบ จำกัด" in all_text      # vendor code stripped
    assert "(งวดที่ 2)" in all_text              # งวด suffix landed in the doc type
    assert "20 กรกฎาคม 2569" in all_text         # start date in Thai


def test_build_letter_uses_selected_nguad_deadline():
    """clean_delivery is wired into the generate path (ARCHITECTURE §13.3):
    with a multi-งวด TOR, the body's deadline comes from the CHOSEN งวด,
    not from whichever งวด appears first in the clause."""
    multi_nguad_tor = ("การส่งมอบงาน\n"
                       "งวดที่ 1 ส่งแผนงานภายใน 15 วัน นับถัดจากวันที่ได้รับหนังสือแจ้ง\n"
                       "งวดที่ 2 ส่งรายงานฉบับสมบูรณ์ภายใน 120 วัน นับถัดจากวันที่ได้รับหนังสือแจ้ง")
    docx_bytes, _fn, _log, _used_ai = letter_builder.build_letter(
        selected_form=FORM_TYPES[0],
        doc_number="PTT-002/2568",
        po_number="4500987654",
        doc_type=DOC_TYPE_OPTIONS[0],
        signer="นายทดสอบ ระบบดี",
        signer_position="",
        lookup_data=LOOKUP,
        start_date=date(2026, 7, 20),
        delivery_raw=multi_nguad_tor,
        selected_nguad={"label": "งวดที่ 2", "number": 2, "manual": False},
        now=datetime(2026, 7, 16, 12, 0, 0),
    )
    doc = Document(BytesIO(docx_bytes))
    all_text = "\n".join(p.text for p in doc.paragraphs)
    assert "ภายใน 120 วัน" in all_text           # the chosen งวด's deadline
    assert "ภายใน 15 วัน" not in all_text        # not งวดที่ 1's


def test_build_letter_keeps_raw_clause_when_cleaning_loses_duration(monkeypatch):
    """Seen live 2026-07-16: the AI paraphrase reworded 'ภายใน 120 วัน' so the strict
    extractor found nothing and the letter lost its deadline sentence. The guard must
    fall back to the raw TOR clause when that happens."""
    import ai_clean

    raw = ("ผู้รับจ้างต้องส่งมอบงานภายใน 120 วัน (ไม่เว้นวันหยุด) "
           "นับถัดจากผู้รับจ้างได้รับใบสั่งจ้างจาก ปตท.")
    paraphrase_without_signal = ("ผู้รับจ้างต้องส่งมอบงานภายในระยะเวลา 120 วัน "
                                 "นับถัดจากได้รับใบสั่งจ้าง")   # 'ภายใน' not followed by digits
    monkeypatch.setattr(ai_clean, "clean_delivery",
                        lambda clause, label=None, retries=2:
                            (paraphrase_without_signal, True))

    docx_bytes, _fn, _log, _used_ai = letter_builder.build_letter(
        selected_form=FORM_TYPES[0],
        doc_number="TEST-002/2569",
        po_number="4500987654",
        doc_type=DOC_TYPE_OPTIONS[0],
        signer="นายทดสอบ ระบบดี",
        signer_position="",
        lookup_data={**LOOKUP, "daySLA": None},
        start_date=date(2026, 7, 20),
        delivery_raw=raw,
        selected_nguad={"label": "งวดเดียว", "number": None, "manual": False},
        now=datetime(2026, 7, 16, 12, 0, 0),
    )
    doc = Document(BytesIO(docx_bytes))
    all_text = "\n".join(p.text for p in doc.paragraphs)
    assert "โดยกำหนดให้แล้วเสร็จภายใน 120 วัน" in all_text   # raw clause won