/* Shared client utilities for TeleCollect Management UI (CSRF, auth guard, safe rendering) */
window.TC = (() => {
let csrfToken = "";
function getCookie(name) {
const m = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/[-.$?*|{}()[\]\\/+^]/g, "\\$&") + "=([^;]*)"));
return m ? decodeURIComponent(m[1]) : "";
}
function esc(str) {
return String(str ?? "")
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """);
}
async function api(url, opts = {}) {
const method = (opts.method || "GET").toUpperCase();
const headers = { ...(opts.headers || {}) };
if (opts.body !== undefined && !(opts.body instanceof FormData)) {
headers["Content-Type"] = "application/json";
}
if (!["GET", "HEAD", "OPTIONS"].includes(method)) {
const tok = csrfToken || getCookie("tc_csrf");
if (tok) headers["X-CSRF-Token"] = tok;
}
const res = await fetch(url, {
...opts,
method,
headers,
credentials: "same-origin",
body: opts.body !== undefined && typeof opts.body !== "string" ? JSON.stringify(opts.body) : opts.body,
});
const text = await res.text();
let data = null;
try { data = text ? JSON.parse(text) : null; } catch { data = { detail: text }; }
if (!res.ok) {
const err = new Error((data && data.detail) || `HTTP ${res.status}`);
err.status = res.status;
err.data = data;
throw err;
}
return data;
}
async function requireAuth(expectedRole = null) {
try {
const me = await api("/api/auth/me");
csrfToken = me.csrf_token || getCookie("tc_csrf");
if (expectedRole && me.user.role !== expectedRole) {
return { forbidden: true, me };
}
return { forbidden: false, me };
} catch (e) {
if (e.status === 401) {
window.location.href = "/login";
return null;
}
throw e;
}
}
async function logout() {
try { await api("/api/auth/logout", { method: "POST" }); } catch {}
window.location.href = "/login";
}
function reviewBadge(status) {
if (status === "approved") return 'Approved';
if (status === "rejected") return 'Rejected';
if (status === "pending") return 'Pending Review';
return 'N/A';
}
function outcomeBadge(ep) {
if (!ep.validation_passed) return 'Technical Fail';
if (ep.task_outcome !== "success" || !ep.full_demonstration) {
return `${esc(ep.task_outcome)}`;
}
return 'Success';
}
return { api, esc, requireAuth, logout, reviewBadge, outcomeBadge, setCsrf: (t) => { csrfToken = t; } };
})();