Menixis Claude Opus 4.8 (1M context) commited on
Commit
b5c887b
·
1 Parent(s): 8433a01

Auto-form: vendor-name cleanup, real PO date, PTT/vendor swap, TOR กำหนดส่งมอบ, signer ตำแหน่ง

Browse files

- streamlit_app: strip leading SAP vendor code from VendorName; convert
poCreateDate Excel serial -> date; resolve SMP signers once per render and
show the TOR กำหนดส่งมอบ (การส่งมอบงาน) clause in the info card; pass signer
position to the form.
- signer_lookup: fold a TOR delivery-clause fetch into the browser resolver
(PROnline.torId -> TOROnline eager:details -> section 7 contentPreview),
returned as deliveryClause; add pick_delivery(); stripHtml helper.
- form_logic: clean_vendor_name(); fill signer_position; PTT/vendor swap uses
the repositioned Vendor token.
- form1.docx: PTT now subject of the body clause; add centered ตำแหน่งผู้ลงนาม
line under the signer name.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Files changed (4) hide show
  1. form_logic.py +23 -2
  2. signer_lookup.py +31 -2
  3. streamlit_app.py +32 -2
  4. templates/form1.docx +2 -2
form_logic.py CHANGED
@@ -7,6 +7,7 @@ Form Logic — pure logic for document generation (no UI dependencies)
7
  """
8
 
9
  import os
 
10
  from docx import Document
11
 
12
 
@@ -41,6 +42,7 @@ PLACEHOLDER_DOC_NUM_F1 = "หมายเลขเอกสาร"
41
  PLACEHOLDER_PO_F1 = "PO_No"
42
  PLACEHOLDER_TYPE_F1 = "แจ้งให้เริ่มเข้าทำงาน / เริ่มส่งมอบสินค้า"
43
  PLACEHOLDER_SIGNER_F1 = "ผู้มีอำนาจอนุมัติ หรือ ประธานกรรมการตรวจรับ"
 
44
  PLACEHOLDER_VENDOR_F1 = "Vendor"
45
  PLACEHOLDER_WORK_F1 = "ชื่องาน"
46
 
@@ -117,12 +119,28 @@ def format_signer_line_f2_5(name):
117
  return center_text_in_parens(name, total_width=44)
118
 
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  # =============================================================================
121
  # Logic หลัก: สร้างเอกสารตามชนิดแบบฟอร์ม
122
  # =============================================================================
123
  def generate_form(form_id, template_path, output_path,
124
  doc_number, po_number, doc_type, signer,
125
- lookup_data=None):
126
  """
127
  สร้างเอกสาร Word จาก template
128
  Args:
@@ -142,7 +160,7 @@ def generate_form(form_id, template_path, output_path,
142
 
143
  doc = Document(template_path)
144
  log = []
145
- vendor_name = (lookup_data or {}).get("VendorName") or ""
146
  work_title = (lookup_data or {}).get("title") or ""
147
 
148
  if form_id == 1:
@@ -159,6 +177,9 @@ def generate_form(form_id, template_path, output_path,
159
  n = replace_text(doc, PLACEHOLDER_SIGNER_F1, signer or "")
160
  log.append(f"ผู้ลงนาม: แทนที่ {n} จุด")
161
 
 
 
 
162
  if vendor_name:
163
  n = replace_text(doc, PLACEHOLDER_VENDOR_F1, vendor_name)
164
  log.append(f"ชื่อคู่สัญญา (Excel): แทนที่ {n} จุด")
 
7
  """
8
 
9
  import os
10
+ import re
11
  from docx import Document
12
 
13
 
 
42
  PLACEHOLDER_PO_F1 = "PO_No"
43
  PLACEHOLDER_TYPE_F1 = "แจ้งให้เริ่มเข้าทำงาน / เริ่มส่งมอบสินค้า"
44
  PLACEHOLDER_SIGNER_F1 = "ผู้มีอำนาจอนุมัติ หรือ ประธานกรรมการตรวจรับ"
45
+ PLACEHOLDER_POSITION_F1 = "ตำแหน่งผู้ลงนาม"
46
  PLACEHOLDER_VENDOR_F1 = "Vendor"
47
  PLACEHOLDER_WORK_F1 = "ชื่องาน"
48
 
 
119
  return center_text_in_parens(name, total_width=44)
120
 
121
 
122
+ # ชื่อคู่สัญญาจาก export มาพร้อมรหัสผู้ขาย (SAP vendor code) นำหน้า เช่น
123
+ # "0010006270 บริษัท ลินเด้ (ประเทศไทย) จำกัด (มหาชน)" — ตัดรหัส (เลข ≥4 หลัก
124
+ # ตามด้วยช่องว่าง/ตัวคั่น) ที่นำหน้าออก
125
+ _VENDOR_CODE_RE = re.compile(r"^\s*\d{4,}[\s\-–—:.]+")
126
+
127
+
128
+ def clean_vendor_name(value):
129
+ """ลบรหัสผู้ขายที่นำหน้าชื่อคู่สัญญาออก คืนค่าชื่อล้วน ๆ
130
+ (คืนค่าเดิมถ้าไม่มีรหัสนำหน้า หรือถ้าตัดแล้วจะเหลือว่าง)."""
131
+ if not value:
132
+ return ""
133
+ text = str(value).strip()
134
+ cleaned = _VENDOR_CODE_RE.sub("", text).strip()
135
+ return cleaned or text
136
+
137
+
138
  # =============================================================================
139
  # Logic หลัก: สร้างเอกสารตามชนิดแบบฟอร์ม
140
  # =============================================================================
141
  def generate_form(form_id, template_path, output_path,
142
  doc_number, po_number, doc_type, signer,
143
+ lookup_data=None, signer_position=None):
144
  """
145
  สร้างเอกสาร Word จาก template
146
  Args:
 
160
 
161
  doc = Document(template_path)
162
  log = []
163
+ vendor_name = clean_vendor_name((lookup_data or {}).get("VendorName"))
164
  work_title = (lookup_data or {}).get("title") or ""
165
 
166
  if form_id == 1:
 
177
  n = replace_text(doc, PLACEHOLDER_SIGNER_F1, signer or "")
178
  log.append(f"ผู้ลงนาม: แทนที่ {n} จุด")
179
 
180
+ n = replace_text(doc, PLACEHOLDER_POSITION_F1, signer_position or "")
181
+ log.append(f"ตำแหน่งผู้ลงนาม: แทนที่ {n} จุด")
182
+
183
  if vendor_name:
184
  n = replace_text(doc, PLACEHOLDER_VENDOR_F1, vendor_name)
185
  log.append(f"ชื่อคู่สัญญา (Excel): แทนที่ {n} จุด")
signer_lookup.py CHANGED
@@ -41,6 +41,13 @@ def pick_position(signers, role):
41
  else signers.get("approverPosition")) or ""
42
 
43
 
 
 
 
 
 
 
 
44
  # Browser-side resolver. __PO__ / __TOKEN__ / __GW__ are substituted in build_signers_js.
45
  # Always resolves to a JSON STRING within ~16s (per-fetch AbortController + overall race-guard),
46
  # so the Python side parse is deterministic. The Report is retried on transient empties.
@@ -50,8 +57,8 @@ _JS_TEMPLATE = r"""
50
  const H = {"Authorization": "__TOKEN__", "Content-Type": "application/json", "Accept": "application/json"};
51
  const PO = "__PO__";
52
  const TIMEOUT_MS = 9000;
53
- const OVERALL_MS = 16000;
54
- const blank = () => ({pr:null, approver:null, approverPosition:null, chairman:null, chairmanPosition:null, error:null});
55
 
56
  const jfetch = async (url, opts) => {
57
  const ac = new AbortController();
@@ -60,6 +67,15 @@ _JS_TEMPLATE = r"""
60
  finally { clearTimeout(t); }
61
  };
62
 
 
 
 
 
 
 
 
 
 
63
  const work = (async () => {
64
  const out = blank();
65
  try {
@@ -121,6 +137,19 @@ _JS_TEMPLATE = r"""
121
  const u = (c.user && typeof c.user === "object") ? c.user : {};
122
  out.chairmanPosition = u.PositionNameTH || c.position_name || null;
123
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  return out;
125
  } catch (err) {
126
  out.error = (err && err.name === "AbortError")
 
41
  else signers.get("approverPosition")) or ""
42
 
43
 
44
+ def pick_delivery(signers):
45
+ """The verbatim 'การส่งมอบงาน' (กำหนดส่งมอบ) clause from the PR's TOR, or ''."""
46
+ if not isinstance(signers, dict):
47
+ return ""
48
+ return signers.get("deliveryClause") or ""
49
+
50
+
51
  # Browser-side resolver. __PO__ / __TOKEN__ / __GW__ are substituted in build_signers_js.
52
  # Always resolves to a JSON STRING within ~16s (per-fetch AbortController + overall race-guard),
53
  # so the Python side parse is deterministic. The Report is retried on transient empties.
 
57
  const H = {"Authorization": "__TOKEN__", "Content-Type": "application/json", "Accept": "application/json"};
58
  const PO = "__PO__";
59
  const TIMEOUT_MS = 9000;
60
+ const OVERALL_MS = 20000;
61
+ const blank = () => ({pr:null, approver:null, approverPosition:null, chairman:null, chairmanPosition:null, deliveryClause:null, error:null});
62
 
63
  const jfetch = async (url, opts) => {
64
  const ac = new AbortController();
 
67
  finally { clearTimeout(t); }
68
  };
69
 
70
+ // strip Froala/HTML to plain text (block tags -> newlines), unescape entities, collapse runs
71
+ const stripHtml = (h) => {
72
+ if (!h) return "";
73
+ h = h.replace(/<(br|\/p|\/div|\/li|\/ol|\/ul)[^>]*>/gi, "\n").replace(/<[^>]+>/g, "");
74
+ const ta = document.createElement("textarea"); ta.innerHTML = h; h = ta.value;
75
+ h = h.split(String.fromCharCode(160)).join(" ");
76
+ return h.split("\n").map(l => l.replace(/[ \t]+/g, " ").trim()).filter(Boolean).join("\n");
77
+ };
78
+
79
  const work = (async () => {
80
  const out = blank();
81
  try {
 
137
  const u = (c.user && typeof c.user === "object") ? c.user : {};
138
  out.chairmanPosition = u.PositionNameTH || c.position_name || null;
139
  }
140
+
141
+ // 5) PR -> TOR delivery clause (การส่งมอบงาน, section 7) — best effort; never blocks the names
142
+ try {
143
+ const torId = inner && inner.torId;
144
+ if (torId) {
145
+ const tflt = encodeURIComponent(JSON.stringify({eager: {details: true, "$where": {id: torId}}}));
146
+ const tor = await jfetch(GW + "/master-service/TOROnline?filter=" + tflt, {headers:H});
147
+ const parts = (((Array.isArray(tor) && tor[0]) || {}).details) || [];
148
+ const part = parts.find(d => (((d.title||"")+(d.content||"")).indexOf("การส่งมอบงาน") >= 0)
149
+ || ((d.content||"").indexOf("กำหนดการส่งมอบ") >= 0));
150
+ if (part) out.deliveryClause = stripHtml(part.contentPreview || part.content || "") || null;
151
+ }
152
+ } catch (_) {}
153
  return out;
154
  } catch (err) {
155
  out.error = (err && err.name === "AbortError")
streamlit_app.py CHANGED
@@ -17,11 +17,17 @@ from datetime import datetime, date
17
  import streamlit as st
18
  import streamlit.components.v1 as components
19
  import openpyxl
 
 
 
 
 
20
 
21
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22
 
23
  from form_logic import (
24
  generate_form,
 
25
  FORM_TYPES,
26
  DOC_TYPE_OPTIONS,
27
  SIGNER_ROLES,
@@ -100,6 +106,13 @@ def lookup_po_in_bytes(po_number, file_bytes, sheet_name=None, po_column="poNo")
100
  for i in range(min(len(headers), len(row))):
101
  if headers[i]:
102
  val = row[i]
 
 
 
 
 
 
 
103
  if isinstance(val, datetime):
104
  val = val.strftime("%Y-%m-%d") if not (val.hour or val.minute) \
105
  else val.strftime("%Y-%m-%d %H:%M")
@@ -1172,6 +1185,13 @@ st.markdown(f"""
1172
  # =============================================================================
1173
  # Two-Column Layout
1174
  # =============================================================================
 
 
 
 
 
 
 
1175
  left_col, right_col = st.columns([1.05, 1], gap="large")
1176
 
1177
 
@@ -1244,7 +1264,7 @@ with left_col:
1244
  st.markdown('<div class="section-title">ข้อมูลที่ถูกดึงมา</div>',
1245
  unsafe_allow_html=True)
1246
 
1247
- vendor = st.session_state.lookup_data.get('VendorName')
1248
  title = st.session_state.lookup_data.get('title')
1249
 
1250
  if vendor:
@@ -1276,6 +1296,13 @@ with left_col:
1276
  val = st.session_state.lookup_data.get(col)
1277
  if val not in (None, ""):
1278
  st.markdown(f"**{label}:** {val}")
 
 
 
 
 
 
 
1279
  else:
1280
  st.markdown("""
1281
  <div class="empty-state">
@@ -1335,17 +1362,19 @@ with right_col:
1335
  disabled=not step1_done)
1336
  # ชื่อผู้ลงนาม: ดึงสดจาก SMP ในเบราว์เซอร์ (LNA ผ่านแล้วตั้งแต่หน้าแรก) — ไม่มีการกรอกเอง
1337
  signer = ""
 
1338
  if signer_role:
1339
  po_val = po_number.strip()
1340
  signers = None
1341
  auto = signer_from_lookup(signer_role)
1342
  if not auto and po_val:
1343
- signers = fetch_signers_for_po(po_val)
1344
  if isinstance(signers, dict) and not signers.get("error"):
1345
  auto = signer_lookup.pick_signer(signers, signer_role)
1346
  if auto:
1347
  signer = auto
1348
  pos = signer_lookup.pick_position(signers, signer_role) if signers else ""
 
1349
  st.success(f":material/check_circle: {signer_role}: **{signer}**" + (f" — {pos}" if pos else ""))
1350
  elif signers is None and po_val:
1351
  st.info(":material/hourglass_top: กำลังดึงชื่อผู้ลงนาม…")
@@ -1398,6 +1427,7 @@ with right_col:
1398
  doc_type=doc_type if selected_form['uses_doc_type'] else "",
1399
  signer=signer.strip(),
1400
  lookup_data=st.session_state.lookup_data,
 
1401
  )
1402
  output_buffer.seek(0)
1403
  output_bytes = output_buffer.getvalue()
 
17
  import streamlit as st
18
  import streamlit.components.v1 as components
19
  import openpyxl
20
+ from openpyxl.utils.datetime import from_excel
21
+
22
+ # คอลัมน์วันที่จาก Power BI export ที่บางครั้งส่งออกมาเป็นเลข serial ของ Excel
23
+ # (เช่น 46153) แทน datetime — ต้องแปลงกลับเป็นวันที่ตอนอ่าน
24
+ DATE_COLUMNS = {"poCreateDate"}
25
 
26
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
27
 
28
  from form_logic import (
29
  generate_form,
30
+ clean_vendor_name,
31
  FORM_TYPES,
32
  DOC_TYPE_OPTIONS,
33
  SIGNER_ROLES,
 
106
  for i in range(min(len(headers), len(row))):
107
  if headers[i]:
108
  val = row[i]
109
+ # date cols จาก Power BI อาจมาเป็นเลข serial ของ Excel — แปลงก่อน
110
+ if headers[i] in DATE_COLUMNS and isinstance(val, (int, float)) \
111
+ and not isinstance(val, bool):
112
+ try:
113
+ val = from_excel(val)
114
+ except (ValueError, OverflowError):
115
+ pass
116
  if isinstance(val, datetime):
117
  val = val.strftime("%Y-%m-%d") if not (val.hour or val.minute) \
118
  else val.strftime("%Y-%m-%d %H:%M")
 
1185
  # =============================================================================
1186
  # Two-Column Layout
1187
  # =============================================================================
1188
+ # Resolve the SMP data (signer names + the TOR กำหนดส่งมอบ clause) ONCE per render.
1189
+ # A single browser fetch feeds both the info card (left) and the signer field (right);
1190
+ # calling fetch_signers_for_po in two places would duplicate the streamlit_js_eval key.
1191
+ _po_for_smp = (st.session_state.get("last_po") or "").strip()
1192
+ resolved_signers = (fetch_signers_for_po(_po_for_smp)
1193
+ if (_po_for_smp and st.session_state.lookup_data) else None)
1194
+
1195
  left_col, right_col = st.columns([1.05, 1], gap="large")
1196
 
1197
 
 
1264
  st.markdown('<div class="section-title">ข้อมูลที่ถูกดึงมา</div>',
1265
  unsafe_allow_html=True)
1266
 
1267
+ vendor = clean_vendor_name(st.session_state.lookup_data.get('VendorName'))
1268
  title = st.session_state.lookup_data.get('title')
1269
 
1270
  if vendor:
 
1296
  val = st.session_state.lookup_data.get(col)
1297
  if val not in (None, ""):
1298
  st.markdown(f"**{label}:** {val}")
1299
+ # กำหนดส่งมอบ (การส่งมอบงาน) — pulled live from the PR's TOR via the SMP fetch
1300
+ delivery = signer_lookup.pick_delivery(resolved_signers)
1301
+ if delivery:
1302
+ st.markdown("**กำหนดส่งมอบ:**")
1303
+ st.markdown(delivery.replace("\n", " \n"))
1304
+ elif resolved_signers is None:
1305
+ st.caption(":material/hourglass_top: กำลังดึงกำหนดส่งมอบ…")
1306
  else:
1307
  st.markdown("""
1308
  <div class="empty-state">
 
1362
  disabled=not step1_done)
1363
  # ชื่อผู้ลงนาม: ดึงสดจาก SMP ในเบราว์เซอร์ (LNA ผ่านแล้วตั้งแต่หน้าแรก) — ไม่มีการกรอกเอง
1364
  signer = ""
1365
+ signer_position = ""
1366
  if signer_role:
1367
  po_val = po_number.strip()
1368
  signers = None
1369
  auto = signer_from_lookup(signer_role)
1370
  if not auto and po_val:
1371
+ signers = resolved_signers # single fetch hoisted above the columns
1372
  if isinstance(signers, dict) and not signers.get("error"):
1373
  auto = signer_lookup.pick_signer(signers, signer_role)
1374
  if auto:
1375
  signer = auto
1376
  pos = signer_lookup.pick_position(signers, signer_role) if signers else ""
1377
+ signer_position = pos
1378
  st.success(f":material/check_circle: {signer_role}: **{signer}**" + (f" — {pos}" if pos else ""))
1379
  elif signers is None and po_val:
1380
  st.info(":material/hourglass_top: กำลังดึงชื่อผู้ลงนาม…")
 
1427
  doc_type=doc_type if selected_form['uses_doc_type'] else "",
1428
  signer=signer.strip(),
1429
  lookup_data=st.session_state.lookup_data,
1430
+ signer_position=signer_position.strip(),
1431
  )
1432
  output_buffer.seek(0)
1433
  output_bytes = output_buffer.getvalue()
templates/form1.docx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7654c421dc054857e8b32d4044a253ad52b611ac72ede5eacb8a94a25b379886
3
- size 167627
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:971e1a55fe3894b3e9e1c1e66a5efb15d8f1bae1304a53c7186753e75fe91f20
3
+ size 167657