Menixis Claude Opus 4.8 (1M context) commited on
Commit
234b73f
·
1 Parent(s): 5c120b3

signer: revive browser-side fetch via Local Network Access (Chrome/Edge 142+)

Browse files

Research + live testing (2026-06-30) overturned the earlier "browser can't reach it" verdict:
Chrome 142 replaced the hard PNA block with a user-grantable Local Network Access permission.
Verified on Edge 149: a fetch from the public HF origin to the private 10.x gateway returns
HTTP 401 (reachable), and `localNetworkAccess` is a grantable permission — i.e. the user's
one-time "Allow" click unblocks it. No IT, no PC component.

- signer_lookup.py: restore build_signers_js (PO→PR→approver→chairman chain, per-fetch
AbortController timeout + Report retry-on-empty + JSON.stringify result). Keep role_kind/
pick_signer/pick_position/SIGNER_COLUMN.
- streamlit_app.py: resolve the signer from (1) DATA_URL columns if present, else (2) a live
browser fetch via streamlit-js-eval (swapped in for the broken streamlit-javascript), else
(3) manual box. Loading state nudges the user to click "Allow" once.
- requirements.txt: streamlit-js-eval (replaces the abandoned streamlit-javascript).

Needs the SMP_TOKEN Space secret (no-reply bearer) and each user to click Allow once per device.

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

Files changed (3) hide show
  1. requirements.txt +1 -0
  2. signer_lookup.py +139 -10
  3. streamlit_app.py +62 -14
requirements.txt CHANGED
@@ -3,3 +3,4 @@ openpyxl>=3.1.0
3
  streamlit>=1.42.0
4
  huggingface_hub>=0.20.0
5
  Authlib>=1.3.2
 
 
3
  streamlit>=1.42.0
4
  huggingface_hub>=0.20.0
5
  Authlib>=1.3.2
6
+ streamlit-js-eval>=0.1.7
signer_lookup.py CHANGED
@@ -1,19 +1,148 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- signer_lookup — classify a ผู้ลงนาม role as approver vs receiving-committee chairman.
4
 
5
- The names are NO LONGER fetched in the browser. A public webpage cannot reach PTT's
6
- internal SMP gateway: it resolves to a private 10.x address and Chrome's Private Network
7
- Access blocks public→private requests (verified live 2026-06-30). Instead the
8
- `approverName` / `chairmanName` columns are filled by the Power BI model, which calls the
9
- SMP gateway during its scheduled refresh THROUGH the on-premises data gateway (personal
10
- mode), and they ride the DATA_URL file the app already reads. See powerquery_signers.pq.
11
 
12
- This module now only maps the chosen role to the column it should read.
 
 
 
 
13
  """
14
 
 
 
 
 
 
15
 
16
  def role_kind(role):
17
- """SIGNER_ROLES label -> 'chairman' | 'approver'.
18
- 'ประธานคณะกรรมการตรวจรับ' contains 'ตรวจรับ' -> chairman; otherwise approver."""
19
  return "chairman" if ("ตรวจรับ" in (role or "")) else "approver"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ signer_lookup — resolve a PO's ผู้มีอำนาจอนุมัติ + ประธานกรรมการตรวจรับ IN THE USER'S BROWSER.
4
 
5
+ The HF server can't reach PTT's internal SMP gateway (private 10.x). The user's browser CAN —
6
+ once the user grants the one-time Chrome/Edge **Local Network Access** permission (browser 142+;
7
+ the user clicks "Allow" on the "connect to any device on your local network" prompt). Verified
8
+ 2026-06-30: a fetch from the public HF origin to the gateway returns HTTP 401 (reachable), and
9
+ `localNetworkAccess` is a grantable permission. The gateway also sends `Access-Control-Allow-Origin: *`.
 
10
 
11
+ This builds the client-side JS chain; `streamlit_js_eval` runs it in the browser and returns the
12
+ names to Python.
13
+
14
+ SECURITY: the no-reply bearer is injected into client-side JS (visible to signed-in users). Accepted
15
+ tradeoff: read-only service account, Entra-gated, only works on the PTT network. Rotate periodically.
16
  """
17
 
18
+ GW = "https://do62001-smp-api-gateway-prd.apps.ocpprd.pttdigital.com"
19
+
20
+ # role label -> which data-file column the app reads first (fast path, if ever populated)
21
+ SIGNER_COLUMN = {"approver": "approverName", "chairman": "chairmanName"}
22
+
23
 
24
  def role_kind(role):
25
+ """SIGNER_ROLES label -> 'chairman' | 'approver'."""
 
26
  return "chairman" if ("ตรวจรับ" in (role or "")) else "approver"
27
+
28
+
29
+ def pick_signer(signers, role):
30
+ """Return the signer NAME for the chosen role from a resolved dict, or ''."""
31
+ if not isinstance(signers, dict):
32
+ return ""
33
+ return (signers.get("chairman") if role_kind(role) == "chairman"
34
+ else signers.get("approver")) or ""
35
+
36
+
37
+ def pick_position(signers, role):
38
+ if not isinstance(signers, dict):
39
+ return ""
40
+ return (signers.get("chairmanPosition") if role_kind(role) == "chairman"
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.
47
+ _JS_TEMPLATE = r"""
48
+ (async () => {
49
+ const GW = "__GW__";
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();
58
+ const t = setTimeout(() => ac.abort(), TIMEOUT_MS);
59
+ try { const r = await fetch(url, Object.assign({signal: ac.signal}, opts || {})); return await r.json(); }
60
+ finally { clearTimeout(t); }
61
+ };
62
+
63
+ const work = (async () => {
64
+ const out = blank();
65
+ try {
66
+ // 1) PO -> SAP PR (Organization_Tracking_Report intermittently returns [] -> retry)
67
+ const repBody = {poNo: PO, showMultiplePR: true, sapPrNo:[], prStatus:[], user_id_or_emp_id:[],
68
+ unitCode:[], role:"", procmethod_unit_code:[], projectNo:[], projectStatus:[], title:"",
69
+ commandMethod:"", commandType:"", procurementMethod:"", subProcurementMethod:"",
70
+ procurementCondition:"", purOrgUnitCode:[], torNo:[], torStatus:[], anNo:[], eaStatus:[],
71
+ teNo:[], teStatus:[]};
72
+ let rows = [];
73
+ for (let attempt = 1; attempt <= 3; attempt++) {
74
+ try {
75
+ const rep = await jfetch(GW + "/gateway-service/v2/Organization_Tracking_Report",
76
+ {method:"POST", headers:H, body: JSON.stringify(repBody)});
77
+ rows = Array.isArray(rep) ? rep : [];
78
+ if (rows.length) break;
79
+ } catch (e) { if (attempt === 3) throw e; }
80
+ if (attempt < 3) await new Promise(r => setTimeout(r, 600 * attempt));
81
+ }
82
+ const row = rows.find(r => String(r["PO No."]) === PO) || rows[0];
83
+ if (!row) { out.error = "ดึงข้อมูล PO ไม่สำเร็จ (ระบบตอบกลับว่างชั่วคราว) — ลองใหม่ หรือกรอกชื่อเอง"; return out; }
84
+ const pr = String(row["SAP PR No."] || "");
85
+ out.pr = pr;
86
+ if (!pr) { out.error = "PO ไม่มี SAP PR No."; return out; }
87
+
88
+ // 2) PR -> approver (ผู้มีอำนาจอนุมัติ)
89
+ const det = await jfetch(GW + "/gateway-service/Organization_Tracking_Details",
90
+ {method:"POST", headers:H, body: JSON.stringify({sapPrNo: pr})});
91
+ const sels = (((det || {})["Selection/PO"] || {}).Selection) || [];
92
+ const sel = sels[0] || {};
93
+ const apprArr = (((sel.detail || [])[0] || {})["ผู้มีอำนาจอนุมัติ"]) || [];
94
+ const apprRaw = String(apprArr[0] || "");
95
+ const apprCode = (apprRaw.match(/^(\d+)/) || [])[1] || "";
96
+ let apprName = apprRaw.replace(/^\d+\s*/, "").trim();
97
+
98
+ // 3) approver title + position via the HR directory (best effort)
99
+ if (apprCode) {
100
+ try {
101
+ const dir = await jfetch(GW + "/ea-service/master/search_directoryInfo?EmployeeID=" + apprCode, {headers:H});
102
+ const e = ((((dir || {}).entries || {}).entry) || [])[0];
103
+ if (e) {
104
+ const full = ((e.INAME || "") + " " + (e.EmployeeNameTH || "")).trim();
105
+ if (full) apprName = full;
106
+ out.approverPosition = e.PositionNameTH || null;
107
+ }
108
+ } catch (_) {}
109
+ }
110
+ out.approver = apprName || null;
111
+
112
+ // 4) PR -> chairman (ประธานกรรมการตรวจรับ = first auditCommittee row)
113
+ const flt = encodeURIComponent(JSON.stringify({eager: {"$where": {sapPrNo: pr}}}));
114
+ const pron = await jfetch(GW + "/master-service/PROnline?filter=" + flt, {headers:H});
115
+ const rec = (Array.isArray(pron) && pron[0]) ? pron[0] : null;
116
+ const inner = rec ? (typeof rec.json === "string" ? JSON.parse(rec.json) : rec.json) : null;
117
+ const ac = (inner && inner.auditCommittee) || [];
118
+ if (ac[0]) {
119
+ const c = ac[0];
120
+ out.chairman = (((c.name || "") + " " + (c.surname || "")).trim()) || null;
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")
127
+ ? "หมดเวลาเชื่อมต่อระบบ (ตรวจสอบว่าอยู่ในเครือข่าย PTT แล้วลองใหม่)" : String(err);
128
+ return out;
129
+ }
130
+ })();
131
+
132
+ const guard = new Promise(res => setTimeout(() => {
133
+ const o = blank(); o.error = "หมดเวลาเชื่อมต่อระบบ — ลองใหม่ หรือกรอกชื่อเอง"; res(o);
134
+ }, OVERALL_MS));
135
+
136
+ const result = await Promise.race([work, guard]);
137
+ return JSON.stringify(result);
138
+ })()
139
+ """
140
+
141
+
142
+ def build_signers_js(po, token):
143
+ """Return the client-side JS that resolves a PO -> {approver, chairman, ...} as a JSON string."""
144
+ bearer = token if str(token).lower().startswith("bearer ") else "Bearer " + str(token)
145
+ return (_JS_TEMPLATE
146
+ .replace("__GW__", GW)
147
+ .replace("__PO__", str(po))
148
+ .replace("__TOKEN__", bearer))
streamlit_app.py CHANGED
@@ -10,6 +10,7 @@
10
 
11
  import os
12
  import sys
 
13
  from io import BytesIO
14
  from datetime import datetime, date
15
 
@@ -29,6 +30,14 @@ from form_logic import (
29
  from auth_gate import require_login, render_topbar
30
  import signer_lookup
31
 
 
 
 
 
 
 
 
 
32
 
33
  # =============================================================================
34
  # Helper: lookup PO ใน Excel bytes
@@ -107,19 +116,18 @@ def lookup_po_in_bytes(po_number, file_bytes, sheet_name=None, po_column="poNo")
107
  # =============================================================================
108
  # ผู้ลงนาม: resolve a signer ROLE → the person's name.
109
  # =============================================================================
110
- # The name is read straight from the PO row loaded via DATA_URL. The two columns
111
- # (approverName / chairmanName) are filled by the Power BI model, which calls the
112
- # PTT-internal SMP gateway during its scheduled refresh THROUGH the on-premises data
113
- # gateway (personal mode). The app never touches the gateway itself: a public webpage
114
- # can't reach the private 10.x host (Chrome Private Network Access blocks public→private),
115
- # so the names ride the same OneDrive bridge that already carries Vendor / Work-title.
116
- # See powerquery_signers.pq for the model-side query that fills these columns.
117
- SIGNER_COLUMN = {"approver": "approverName", "chairman": "chairmanName"}
118
 
119
 
120
  def signer_from_lookup(role):
121
- """Signer ROLE -> the person's name, read from the loaded PO row (lookup_data).
122
- Returns "" when the column is absent/blank (the UI then offers manual entry)."""
123
  if not role:
124
  return ""
125
  data = st.session_state.get("lookup_data") or {}
@@ -127,6 +135,35 @@ def signer_from_lookup(role):
127
  return str(data.get(col) or "").strip()
128
 
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  # =============================================================================
131
  # Config: live data source — OneDrive "anyone with the link" (ตั้งใน Space secret DATA_URL)
132
  # =============================================================================
@@ -1250,16 +1287,27 @@ with right_col:
1250
  placeholder="เลือกผู้มีอำนาจลงนาม",
1251
  key="signer_role_widget",
1252
  disabled=not step1_done)
1253
- # ชื่อผู้ลงนามถูกเติมมากับข้อมูล PO (คอลัมน์ approverName/chairmanName ที่ Power BI ดึงผ่าน
1254
- # on-prem gateway) — อ่านจาก lookup_data ตรง ๆ; ถ้าไม่มีก็ให้กรอกเอง
1255
  signer = ""
1256
  if signer_role:
 
 
1257
  auto = signer_from_lookup(signer_role)
 
 
 
 
1258
  if auto:
1259
  signer = auto
1260
- st.success(f":material/check_circle: {signer_role}: **{signer}**")
 
 
 
 
 
 
1261
  else:
1262
- st.warning(":material/edit: ไม่มีชื่อผู้ลงนามในข้อมูล PO นี้ — กรอกชื่อผู้ลงนามเอง")
1263
  signer = st.text_input("ชื่อผู้ลงนาม", key="signer_manual_widget").strip()
1264
  # remember the resolved name for the stepper comparison (read at the top next render)
1265
  st.session_state["current_signer_name"] = signer
 
10
 
11
  import os
12
  import sys
13
+ import json
14
  from io import BytesIO
15
  from datetime import datetime, date
16
 
 
30
  from auth_gate import require_login, render_topbar
31
  import signer_lookup
32
 
33
+ # Browser-side JS bridge: runs the signer fetch in the USER'S browser, which — unlike the HF
34
+ # server — can reach the PTT-internal gateway after the user grants the one-time Local Network
35
+ # Access "Allow" (Chrome/Edge 142+). Optional import so the app still runs (manual entry) if absent.
36
+ try:
37
+ from streamlit_js_eval import streamlit_js_eval
38
+ except Exception: # noqa: BLE001
39
+ streamlit_js_eval = None
40
+
41
 
42
  # =============================================================================
43
  # Helper: lookup PO ใน Excel bytes
 
116
  # =============================================================================
117
  # ผู้ลงนาม: resolve a signer ROLE → the person's name.
118
  # =============================================================================
119
+ # Two sources, in order: (1) the PO row from DATA_URL if it already carries
120
+ # approverName/chairmanName (fast, no fetch); else (2) a LIVE fetch in the USER'S browser to
121
+ # the SMP gateway — the HF server can't reach the private gateway, but the user's browser can
122
+ # after a one-time Local Network Access "Allow" (Chrome/Edge 142+; verified reachable 2026-06-30).
123
+ # Manual entry is always the fallback. See signer_lookup.build_signers_js for the browser chain.
124
+ SIGNER_COLUMN = signer_lookup.SIGNER_COLUMN
125
+ # no-reply read-only bearer (Space secret) — injected into the browser-side fetch.
126
+ SMP_TOKEN = os.environ.get("SMP_TOKEN", "").strip()
127
 
128
 
129
  def signer_from_lookup(role):
130
+ """Fast path: signer name from the loaded PO row (lookup_data), or '' if the column is absent."""
 
131
  if not role:
132
  return ""
133
  data = st.session_state.get("lookup_data") or {}
 
135
  return str(data.get(col) or "").strip()
136
 
137
 
138
+ def fetch_signers_for_po(po):
139
+ """Resolve {approver, chairman, ...} via a fetch in the user's browser (streamlit_js_eval).
140
+ Returns a dict on success, {"error": ...} on failure, or None while still resolving
141
+ (incl. before the user clicks the one-time Local Network Access 'Allow')."""
142
+ po = (po or "").strip()
143
+ if not po:
144
+ return {"error": "no po"}
145
+ cache = st.session_state.setdefault("_signers_cache", {})
146
+ if po in cache:
147
+ return cache[po]
148
+ if not streamlit_js_eval:
149
+ return {"error": "browser bridge unavailable"}
150
+ if not SMP_TOKEN:
151
+ return {"error": "no SMP_TOKEN configured"}
152
+ js = signer_lookup.build_signers_js(po, SMP_TOKEN)
153
+ res = streamlit_js_eval(js_expressions=js, key=f"sig_{po}", want_output=True)
154
+ if isinstance(res, dict):
155
+ cache[po] = res
156
+ return res
157
+ if isinstance(res, str) and res.strip().startswith("{"):
158
+ try:
159
+ d = json.loads(res)
160
+ cache[po] = d
161
+ return d
162
+ except Exception: # noqa: BLE001
163
+ return {"error": "bad response"}
164
+ return None # still resolving
165
+
166
+
167
  # =============================================================================
168
  # Config: live data source — OneDrive "anyone with the link" (ตั้งใน Space secret DATA_URL)
169
  # =============================================================================
 
1287
  placeholder="เลือกผู้มีอำนาจลงนาม",
1288
  key="signer_role_widget",
1289
  disabled=not step1_done)
1290
+ # ชื่อผู้ลงนาม: (1) จากข้อมู��� PO ถ้ามี → (2) ดึงสดในเบราว์เซอร์ผ่าน SMP (กด Allow ครั้งแรก) → (3) กรอกเอง
 
1291
  signer = ""
1292
  if signer_role:
1293
+ po_val = po_number.strip()
1294
+ signers = None
1295
  auto = signer_from_lookup(signer_role)
1296
+ if not auto and po_val:
1297
+ signers = fetch_signers_for_po(po_val)
1298
+ if isinstance(signers, dict) and not signers.get("error"):
1299
+ auto = signer_lookup.pick_signer(signers, signer_role)
1300
  if auto:
1301
  signer = auto
1302
+ pos = signer_lookup.pick_position(signers, signer_role) if signers else ""
1303
+ st.success(f":material/check_circle: {signer_role}: **{signer}**" + (f" — {pos}" if pos else ""))
1304
+ elif signers is None and po_val:
1305
+ st.info(":material/hourglass_top: กำลังดึงชื่อผู้ลงนาม… "
1306
+ "ครั้งแรกให้กด **Allow** ที่ป๊อปอัป \"เชื่อมต่ออุปกรณ์ในเครือข่าย\" แล้วรอสักครู่ "
1307
+ "(หรือกรอกชื่อเองด้านล่าง)")
1308
+ signer = st.text_input("ชื่อผู้ลงนาม", key="signer_manual_widget").strip()
1309
  else:
1310
+ st.warning(":material/edit: ดึงชื่ออัตโนมัติไม่ได้ — กรอกชื่อผู้ลงนามเอง")
1311
  signer = st.text_input("ชื่อผู้ลงนาม", key="signer_manual_widget").strip()
1312
  # remember the resolved name for the stepper comparison (read at the top next render)
1313
  st.session_state["current_signer_name"] = signer