(function () {
let currentPage = document.body.dataset.page || "home";
const pageContent = document.getElementById("pageContent");
const recordModal = document.getElementById("recordModal");
const recordModalLabel = document.getElementById("recordModalLabel");
const recordModalBody = document.getElementById("recordModalBody");
const modalPrimaryAction = document.getElementById("modalPrimaryAction");
const modalRemoteAction = document.getElementById("modalRemoteAction");
const searchInput = document.getElementById("globalSearch");
const modalInstance = recordModal && window.bootstrap ? new window.bootstrap.Modal(recordModal) : null;
const storageService = window.BeaStorageService;
const profileManager = window.BeaProfileManager;
const apiService = window.BeaApiService;
const dataCacheVersion = "20261026200108";
const dateTimeDisplayFormatter = new Intl.DateTimeFormat("en-US", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit"
});
const dataUrls = {
requests: "https://www.xenhey.com/api/store/C63D8DAACE884EE284AC07E4D848250E",
providers: "https://www.xenhey.com/api/store/BF43AE7B2DAC475586AEBE7C3656B37F",
cases: "https://www.xenhey.com/api/store/3CC5D356AAEA46158CA38173467C082D",
reports: "https://www.xenhey.com/api/store/D80D1A98CE86498694AD12CE1CB84D84",
veterans: "https://www.xenhey.com/api/store/457726C2705148DF805B2ADD47A9AE0B",
coordinatedEntry: "https://www.xenhey.com/api/store/493815A858FE4341B2F49A7B2F48C314",
consents: "https://www.xenhey.com/api/store/9F6E17F47AAD47DF9595F57F14E1317B",
units: "https://www.xenhey.com/api/store/794F21BF39EA4DDAA16E1C6ABA5A64F5",
partnerOperations: "https://www.xenhey.com/api/store/18EB1C941F0446C3B33945C4E88FFAA9",
assuranceControls: "https://www.xenhey.com/api/store/A74AB5125AC14141B6E3403892D823B8"
};
const datasourceTables = {
requests: "requestTable",
providers: "providerTable",
cases: "caseTable",
reports: "reportTable",
placements: "placementTable",
veterans: "veteranTable",
coordinatedEntry: "assessmentTable",
consents: "consentTable",
units: "unitTable",
partnerOperations: "partnerOperationsTable"
};
const tableDatasources = {
homeRequests: "requests",
requestTable: "requests",
providerTable: "providers",
caseTable: "cases",
reportTable: "reports",
placementTable: "placements",
veteranTable: "veterans",
assessmentTable: "coordinatedEntry",
consentTable: "consents",
unitTable: "units",
partnerOperationsTable: "partnerOperations",
assuranceControlTable: "assuranceControls"
};
const tableStore = {};
const pendingDatasets = {};
const tableRegistry = {};
const tableSourceRows = {};
const connectedModalRecords = {};
const connectedModalTables = {};
const versionedTableIds = new Set(["veteranTable", "assessmentTable", "consentTable", "unitTable", "partnerOperationsTable"]);
const scenarioFormFieldKeys = new Set([
"scenarioid",
"scenariofamily",
"scenariovariant",
"scenariotype",
"scenariostep",
"expectedoutcome",
"expectedvalidation",
"expectedkpieffects",
"testtags",
"journeystage",
"dataqualitystatus"
]);
let modalState = null;
let activeProfile = null;
let activeDrilldown = readDrilldownFromUrl();
let sessionAssurance = null;
const pageDefinitions = {
login: { title: "Sign in to a browser-local BeaReponseCare workspace.", render: renderLogin },
home: { title: "Operational overview for veteran accommodation placement, provider readiness, and case-manager response.", render: renderHome },
requests: { title: "Guided veteran intake, urgency triage, and request workflow monitoring.", render: renderRequests },
providers: { title: "Hotel, housing, and shelter network availability across South Jersey.", render: renderProviders },
cases: { title: "Case manager workflows for review, matching, approvals, and stay extensions.", render: renderCases },
placement: { title: "Shared triage, matching, approval, reservation, stay, finance, and communications operations.", render: renderPlacementOperations },
partnerOperations: { title: "Closed-loop provider responses, SLA work, event notifications, extensions, transitions, and exception resolution.", render: renderPartnerOperations },
veterans: { title: "Unified veteran profiles, households, eligibility, programs, ownership, and duplicate resolution.", render: renderVeteran360 },
coordinatedEntry: { title: "Standardized housing-crisis assessment, vulnerability scoring, prioritization, and referral decisions.", render: renderCoordinatedEntry },
availability: { title: "Real-time South Jersey bed and unit inventory, holds, conflicts, accessibility, and check-in status.", render: renderAvailabilityBoard },
consent: { title: "Veteran permissions, information categories, effective dates, signatures, revocations, and disclosure history.", render: renderConsentCenter },
reports: { title: "Program utilization, funding visibility, and export-ready operational reporting.", render: renderReports },
versionHistory: { title: "Application releases, supporting evidence, and production roadmap gates.", render: renderVersionHistory },
serviceOperations: { title: "Data quality, service levels, integration health, resilience, accessibility, incidents, and release assurance.", render: renderServiceOperations },
assurance: { title: "Operational control register for all 102 reflection-question implementation requirements.", render: renderAssuranceWorkbench }
};
const pageChrome = {
home: { heading: "Command Center", kicker: "Mission Control", search: "Search operations, requests, and highlights", action: "New Record", footerKicker: "Coverage", footerTitle: "Always-on support coordination", footerNote: "Live request, provider, and case visibility across South Jersey." },
requests: { heading: "Veteran Requests", kicker: "Veteran Intake And Routing", search: "Search requests, veterans, urgency", action: "New Intake", footerKicker: "Request visibility", footerTitle: "Critical queue monitored", footerNote: "Escalation rules remain active across all seven South Jersey counties." },
providers: { heading: "Providers", kicker: "Supply And Provider Capacity", search: "Search provider, city, capacity", action: "Add Provider", footerKicker: "Provider network", footerTitle: "Readiness tracked hourly", footerNote: "Accessible inventory, shuttle support, and pet policy coverage stay visible." },
cases: { heading: "Case Management", kicker: "Review, Match, Track, Close", search: "Search case, manager, milestone", action: "Create Case", footerKicker: "Case flow", footerTitle: "Approvals within SLA", footerNote: "Average assignment time remains visible for review and coaching." },
placement: { heading: "Agent Placement", kicker: "Triage, Match, Approve, Confirm", search: "Search placement, veteran, provider, reservation", action: "New Placement", footerKicker: "Shared workflow", footerTitle: "Placement decisions tracked", footerNote: "Triage, holds, approvals, reservations, and stay events remain connected." },
partnerOperations: { heading: "Agent Operations", kicker: "Respond, Escalate, Resolve", search: "Search work item, placement, veteran, provider", action: "New Work Item", footerKicker: "Closed-loop operations", footerTitle: "Every handoff accountable", footerNote: "Provider decisions, deadlines, delivery results, transitions, and exceptions stay connected." },
veterans: { heading: "Veteran 360", kicker: "One Veteran, One Coordinated Record", search: "Search veteran, household, eligibility, owner", action: "Add Veteran", footerKicker: "Unified profile", footerTitle: "Duplicate-safe coordination", footerNote: "Households, eligibility, programs, and accountable owners remain connected." },
coordinatedEntry: { heading: "Coordinated Entry", kicker: "Assess, Prioritize, Refer", search: "Search assessment, veteran, priority, referral", action: "New Assessment", footerKicker: "Standard assessment", footerTitle: "Explainable prioritization", footerNote: "Scores, eligibility, overrides, and referral decisions remain auditable." },
availability: { heading: "Bed & Unit Board", kicker: "Inventory, Holds, Check-In", search: "Search unit, provider, county, hold, accessibility", action: "Add Unit", footerKicker: "Live inventory", footerTitle: "Reservation conflicts visible", footerNote: "Availability, accessibility, hold expiration, and check-in stay synchronized." },
consent: { heading: "Consent Center", kicker: "Permission, Purpose, Disclosure", search: "Search consent, veteran, organization, status", action: "New Consent", footerKicker: "Consent controls", footerTitle: "Minimum necessary sharing", footerNote: "Permitted organizations, data categories, dates, and revocations remain visible." },
reports: { heading: "Reports", kicker: "Performance, Funding, Outcomes", search: "Search report, region, metric", action: "Run Report", footerKicker: "Reporting", footerTitle: "Published metrics ready", footerNote: "Export-friendly views stay aligned with hosted sample records." },
versionHistory: { heading: "Version History", kicker: "Release Evidence And Roadmap", search: "Search releases, capabilities, and roadmap gates", action: "Current Version", footerKicker: "Release governance", footerTitle: "Evidence before promotion", footerNote: "Version, source, actor, time, and readiness evidence stay visible." },
serviceOperations: { heading: "Service Operations", kicker: "Observe, Rehearse, Improve", search: "Search controls, SLOs, incidents, and release gates", action: "Run Readiness Check", footerKicker: "Service assurance", footerTitle: "Risk visible before release", footerNote: "Data quality, resilience, accessibility, and support evidence remain connected." },
assurance: { heading: "Assurance Workbench", kicker: "Evidence, Ownership, Readiness", search: "Search control, chapter, owner, evidence", action: "New Control", footerKicker: "Implementation assurance", footerTitle: "Every requirement accountable", footerNote: "Owners, evidence, verification, dependencies, and production boundaries remain visible." }
};
const allWorkspacePages = Object.keys(pageChrome);
const rolePageAccess = {
"Care Operations": ["home", "requests", "veterans", "coordinatedEntry", "consent", "cases", "placement", "partnerOperations"],
"Case Manager": ["home", "requests", "veterans", "coordinatedEntry", "consent", "cases", "placement", "partnerOperations"],
"Coordinated Entry Assessor": ["home", "requests", "veterans", "coordinatedEntry", "consent", "cases"],
"Consent Steward": ["home", "veterans", "coordinatedEntry", "consent"],
"Inventory Coordinator": ["home", "providers", "availability", "placement", "partnerOperations"],
"Provider Success": ["home", "providers", "availability", "placement", "partnerOperations"],
"Program Analytics": ["home", "reports"],
"Government Programs": ["home", "requests", "cases", "reports", "versionHistory"],
"Proposal Manager": ["home", "reports", "versionHistory"],
"System Administrator": allWorkspacePages
};
function canAccessPage(pageKey) {
if (pageKey === "login") return true;
return (rolePageAccess[activeProfile?.role] || ["home"]).includes(pageKey);
}
function applyRoleScope() {
document.querySelectorAll("#mobileSidebar .nav-link[data-nav-key]").forEach((link) => {
const allowed = canAccessPage(link.dataset.navKey);
link.classList.toggle("d-none", !allowed);
link.setAttribute("aria-hidden", allowed ? "false" : "true");
link.tabIndex = allowed ? 0 : -1;
});
document.querySelectorAll("[data-nav-page]").forEach((control) => {
const allowed = canAccessPage(control.dataset.navPage);
control.classList.toggle("d-none", !allowed);
control.disabled = !allowed;
});
document.body.dataset.roleScope = activeProfile?.role || "Unscoped";
}
const pageRefreshConfig = {
home: { label: "command center", datasets: ["requests", "providers", "cases"], tableId: "homeRequests" },
requests: { label: "veteran requests", datasets: ["requests"], tableId: "requestTable" },
providers: { label: "provider", datasets: ["providers"], tableId: "providerTable" },
cases: { label: "case management", datasets: ["cases"], tableId: "caseTable" },
partnerOperations: { label: "agent operations", datasets: ["partnerOperations", "requests", "cases", "providers", "veterans"], tableId: "partnerOperationsTable" },
veterans: { label: "Veteran 360", datasets: ["veterans", "requests", "providers", "coordinatedEntry", "consents"], tableId: "veteranTable" },
coordinatedEntry: { label: "coordinated entry", datasets: ["coordinatedEntry", "veterans", "providers"], tableId: "assessmentTable" },
availability: { label: "bed and unit availability", datasets: ["units", "providers", "cases"], tableId: "unitTable" },
consent: { label: "consent center", datasets: ["consents", "veterans"], tableId: "consentTable" },
reports: { label: "reporting", datasets: ["reports", "requests", "cases"], tableId: "reportTable" },
assurance: { label: "assurance controls", datasets: ["assuranceControls"], tableId: "assuranceControlTable" }
};
init();
async function init() {
injectSharedStyles();
if (!storageService || !profileManager || !apiService) {
throw new Error("The portal service modules did not load.");
}
await storageService.initialize();
if (currentPage === "login") {
await renderLogin();
return;
}
activeProfile = profileManager.getActiveProfile();
if (!activeProfile) {
redirectToLogin();
return;
}
if (!canAccessPage(currentPage)) {
const homeUrl = document.body.dataset.homeUrl;
if (homeUrl && !homeUrl.startsWith("__")) {
window.location.replace(homeUrl);
return;
}
currentPage = "home";
}
initializeSessionAssurance();
bindMobileSidebar();
bindChromeActions();
bindFastNavigation();
renderProfileChrome();
applyRoleScope();
if (searchInput) {
searchInput.addEventListener("input", handleGlobalSearch);
}
window.history.replaceState({ brcPage: currentPage, drilldown: activeDrilldown }, "", window.location.href);
window.addEventListener("popstate", handleHistoryNavigation);
await renderPage(currentPage, { announce: false });
warmNavigationAssets();
}
async function renderPage(pageKey, options = {}) {
const definition = pageDefinitions[pageKey];
if (!definition) {
window.location.href = options.href || document.body.dataset.homeUrl;
return;
}
if (!canAccessPage(pageKey)) {
showToast("Access restricted", `${activeProfile.role} does not have access to ${pageChrome[pageKey]?.heading || pageKey}.`, "danger");
if (pageKey !== "home") {
await navigateToPage("home", document.body.dataset.homeUrl, { announce: false });
}
return;
}
searchInput?._placementSearchCleanup?.();
searchInput?._pageSearchCleanup?.();
searchInput?._pageRefreshCleanup?.();
showLoadingState();
try {
await definition.render();
renderOperationalReadinessBanner(pageKey);
renderP0AssuranceBanner(pageKey);
renderPdfTakeawayPanel(pageKey);
if (pageRefreshConfig[pageKey]) {
bindPageRefresh(pageKey, pageRefreshConfig[pageKey]);
bindPageHeaderSearch(pageKey, pageRefreshConfig[pageKey].tableId);
}
bindNavigationButtons();
applyRoleScope();
applyTableDrilldown(options.drilldown || activeDrilldown);
if (options.announce !== false) {
showToast("Page ready", definition.title, "success");
}
} catch (error) {
console.error("BeaReponseCare page load failed", error);
pageContent.innerHTML = `
Data load issue
We could not load the hosted data for this page.
Refresh the page or republish the JSON feeds if the hosted data changed.
`;
showToast("Load failed", "Hosted JSON could not be loaded for this page.", "danger");
}
}
function evaluateRecordReadiness(tableId, record) {
const issues = [];
const add = (field, message) => issues.push({ field, message });
const value = (key) => String(record?.[key] ?? "").trim();
const number = (key) => Number(record?.[key]);
const parsed = (key) => Date.parse(record?.[key] || "");
const requireFields = (fields) => fields.forEach(([field, label]) => {
if (!value(field)) add(field, `${label} is required.`);
});
if (tableId === "requestTable" || tableId === "homeRequests") {
requireFields([["id", "Request ID"], ["veteran", "Veteran"], ["requestedCheckIn", "Check-in"], ["requestedCheckOut", "Check-out"], ["priority", "Priority"], ["status", "Status"]]);
if (Number.isFinite(number("guests")) && (number("guests") < 1 || number("guests") > 10)) add("guests", "Guests must be between 1 and 10.");
if (Number.isFinite(parsed("requestedCheckIn")) && Number.isFinite(parsed("requestedCheckOut")) && parsed("requestedCheckOut") <= parsed("requestedCheckIn")) add("requestedCheckOut", "Check-out must be after check-in.");
if (["Approved", "Assigned", "Checked In", "Closed"].includes(value("status")) && !value("caseId")) add("caseId", "Approved and active requests require a case ID.");
if (["Assigned", "Checked In", "Closed"].includes(value("status")) && !value("providerId")) add("providerId", "Assigned requests require a provider ID.");
} else if (tableId === "providerTable") {
requireFields([["providerId", "Provider ID"], ["name", "Provider name"], ["county", "County"], ["status", "Status"], ["lastInventoryCheck", "Inventory confirmation"]]);
if (number("capacity") < 0 || number("availableUnits") < 0 || number("availableUnits") > number("capacity")) add("availableUnits", "Available units must be between zero and total capacity.");
if (number("accessibleRooms") < 0 || number("accessibleRooms") > number("capacity")) add("accessibleRooms", "Accessible units cannot exceed total capacity.");
if (value("status") === "Available" && number("availableUnits") < 1) add("status", "An available provider must report at least one unit.");
} else if (tableId === "caseTable") {
requireFields([["caseId", "Case ID"], ["requestId", "Request ID"], ["veteran", "Veteran"], ["manager", "Case manager"], ["nextStep", "Next step"]]);
if (["Active Stay Monitoring", "Provider Confirmation", "Extension Review"].includes(value("phase")) && !value("providerId")) add("providerId", "This phase requires an accountable provider.");
if (value("status") === "Closed" && !/outcome|transition|close/i.test(`${value("phase")} ${value("nextStep")}`)) add("nextStep", "Closed cases must document an outcome or transition action.");
} else if (tableId === "placementTable") {
requireFields([["placementId", "Placement ID"], ["caseId", "Case ID"], ["requestId", "Request ID"], ["veteran", "Veteran"], ["assignedOwner", "Case manager"]]);
} else if (tableId === "veteranTable") {
requireFields([["veteranId", "Veteran ID"], ["veteranName", "Veteran name"], ["householdId", "Household ID"], ["eligibilityStatus", "Eligibility"], ["duplicateStatus", "Duplicate review"]]);
if (number("householdSize") < 1) add("householdSize", "Household size must be at least one.");
} else if (tableId === "assessmentTable") {
requireFields([["assessmentId", "Assessment ID"], ["veteranId", "Veteran ID"], ["recommendedPriority", "Recommended priority"], ["finalPriority", "Final priority"], ["referralDecision", "Referral decision"]]);
if (number("vulnerabilityScore") < 0 || number("vulnerabilityScore") > 20) add("vulnerabilityScore", "Vulnerability score must be between 0 and 20.");
if (value("recommendedPriority") !== value("finalPriority") && (!/approved override/i.test(value("overrideStatus")) || !value("overrideReason"))) add("overrideReason", "A changed final priority requires an approved override and reason.");
} else if (tableId === "consentTable") {
requireFields([["consentId", "Consent ID"], ["veteranId", "Veteran ID"], ["permittedOrganization", "Permitted organization"], ["informationCategories", "Information categories"], ["purpose", "Purpose"], ["effectiveDate", "Effective date"], ["expirationDate", "Expiration date"]]);
if (Number.isFinite(parsed("effectiveDate")) && Number.isFinite(parsed("expirationDate")) && parsed("expirationDate") <= parsed("effectiveDate")) add("expirationDate", "Expiration must be after the effective date.");
if (value("revocationStatus") === "Revoked" && !value("revokedAt")) add("revokedAt", "Revoked consent requires a revocation time.");
if (value("status") === "Active" && value("revocationStatus") === "Revoked") add("status", "Revoked consent cannot remain active.");
} else if (tableId === "unitTable") {
requireFields([["unitId", "Unit ID"], ["providerId", "Provider ID"], ["status", "Status"], ["lastInventoryCheck", "Inventory confirmation"]]);
if (number("capacity") < 1) add("capacity", "Unit capacity must be at least one.");
if (value("status") === "Held" && (!value("holdId") || !Number.isFinite(parsed("holdExpiresAt")))) add("holdId", "Held units require a hold ID and expiration.");
if (["Reserved", "Occupied"].includes(value("status")) && (!value("reservationId") || !value("placementId") || !value("caseId"))) add("reservationId", "Reserved and occupied units require reservation, placement, and case references.");
if (value("status") === "Occupied" && !Number.isFinite(parsed("checkedInAt"))) add("checkedInAt", "Occupied units require a check-in time.");
} else if (tableId === "partnerOperationsTable") {
requireFields([["coordinationId", "Work item ID"], ["workType", "Workflow"], ["placementId", "Placement ID"], ["owner", "Owner"], ["actionDeadline", "Deadline"], ["status", "Status"], ["nextAction", "Next action"]]);
if (value("status") === "Completed" && /^(|pending|open)$/i.test(value("actionOutcome"))) add("actionOutcome", "Completed work requires a final outcome.");
if (value("workType") === "Event Notification" && value("status") === "Completed" && value("deliveryStatus") !== "Delivered") add("deliveryStatus", "Completed notifications require confirmed delivery.");
} else if (tableId === "reportTable") {
if (number("requests") < 0 || number("placements") < 0 || number("placements") > number("requests")) add("placements", "Placements must be between zero and total requests.");
if (number("averageHours") < 0) add("averageHours", "Average hours cannot be negative.");
}
return issues;
}
function applyRecordValidation(form, tableId, record) {
form.querySelectorAll("[data-validation-summary]").forEach((element) => element.remove());
Array.from(form.elements).forEach((control) => control.setCustomValidity?.(""));
const issues = evaluateRecordReadiness(tableId, record);
issues.forEach((issue) => form.elements.namedItem(issue.field)?.setCustomValidity?.(issue.message));
if (!issues.length) return true;
const summary = document.createElement("div");
summary.className = "alert alert-danger border mb-3";
summary.dataset.validationSummary = "true";
summary.setAttribute("role", "alert");
summary.innerHTML = `Review ${issues.length} validation item${issues.length === 1 ? "" : "s"}
${issues.map((issue) => `${escapeHtml(issue.message)} `).join("")} `;
form.prepend(summary);
form.elements.namedItem(issues[0].field)?.focus?.();
showToast("Validation required", issues[0].message, "danger");
return false;
}
function clearStaleRecordValidation(form) {
form.querySelectorAll("[data-validation-summary]").forEach((element) => element.remove());
Array.from(form.elements).forEach((control) => control.setCustomValidity?.(""));
}
function bindRecordValidationReset(form) {
if (!form || form.dataset.validationResetBound === "true") return;
form.dataset.validationResetBound = "true";
const resetControl = (event) => {
event.target?.setCustomValidity?.("");
form.querySelector("[data-validation-summary]")?.remove();
};
form.addEventListener("input", resetControl);
form.addEventListener("change", resetControl);
}
function renderOperationalReadinessBanner(pageKey) {
if (!pageContent || pageKey === "login") return;
const datasetKeys = pageRefreshConfig[pageKey]?.datasets
|| (pageKey === "placement" ? ["requests", "cases", "providers"] : []);
const rows = datasetKeys.flatMap((key) => getEffectiveDatasourceRows(key));
if (!rows.length) return;
const nowTime = Date.now();
const fresh = rows.filter((record) => nowTime - Date.parse(record.lastInventoryCheck || record.updatedAt || record.createdAt || 0) <= 24 * 60 * 60 * 1000).length;
const issueCount = datasetKeys.reduce((total, key) => {
const tableId = datasourceTables[key];
return total + (tableId ? getEffectiveDatasourceRows(key).filter((record) => evaluateRecordReadiness(tableId, record).length).length : 0);
}, 0);
const localCount = rows.filter((record) => record.__localOverride || record.__localRecordId).length;
const section = document.createElement("section");
section.className = "section-card operational-readiness-card";
section.dataset.operationalReadiness = pageKey;
section.innerHTML = `
Operational readiness Freshness, validation, and local state Book-aligned controls surface records requiring review before they become downstream decisions.
${issueCount ? `${issueCount} review item${issueCount === 1 ? "" : "s"}` : "Validation clear"}
Connected records ${rows.length}
Needs review ${issueCount}
Local changes ${localCount}
`;
pageContent.prepend(section);
}
function initializeSessionAssurance() {
const key = "p0-session-assurance";
const now = Date.now();
const idleLimitMs = 30 * 60 * 1000;
const existing = storageService.readSession(key, null);
sessionAssurance = existing?.profileId === activeProfile.profileId
? existing
: { sessionId: `SES-${now}-${Math.random().toString(36).slice(2, 8)}`, profileId: activeProfile.profileId, startedAt: new Date(now).toISOString(), lastActivityAt: new Date(now).toISOString(), expiresAt: new Date(now + idleLimitMs).toISOString() };
storageService.writeSession(key, sessionAssurance);
let lastRecorded = 0;
const refresh = () => {
const activityTime = Date.now();
if (activityTime - lastRecorded < 30000) return;
lastRecorded = activityTime;
sessionAssurance.lastActivityAt = new Date(activityTime).toISOString();
sessionAssurance.expiresAt = new Date(activityTime + idleLimitMs).toISOString();
storageService.writeSession(key, sessionAssurance);
};
["pointerdown", "keydown", "touchstart"].forEach((eventName) => document.addEventListener(eventName, refresh, { passive: true }));
window.setInterval(async () => {
if (Date.parse(sessionAssurance.expiresAt) > Date.now()) return;
recordActivity("session-expired", "Session expired", "The prototype session reached its 30-minute inactivity limit.", "Completed");
apiService?.clearCredential?.();
profileManager.logout();
await storageService.flush();
window.location.href = `${document.body.dataset.loginUrl}?sessionExpired=1`;
}, 30000);
}
function renderP0AssuranceBanner(pageKey) {
if (!pageContent || pageKey === "login") return;
const section = document.createElement("section");
section.className = "section-card border border-primary-subtle";
section.dataset.p0Assurance = pageKey;
section.innerHTML = `
P0 trust context Scoped access and operation assurance These controls strengthen the prototype. Production still requires verified identity, server authorization, protected secrets, and authoritative audit infrastructure.
Prototype boundary
Tenant ${escapeHtml(getTenantId())}
Role ${escapeHtml(activeProfile.role)}
Access scope ${activeProfile.role === "System Administrator" ? "All workflows" : "Assigned workflows"}
Session 30-minute idle limit
Audit and sync Local evidence + durable receipts
`;
pageContent.prepend(section);
}
function renderPdfTakeawayPanel(pageKey) {
const takeaways = {
home: {
chapter: "Chapters 1-2",
title: "Coordinate one journey across focused records",
items: ["Use stable identifiers to connect person, request, decision, handoff, and outcome records.", "Surface conflicting values for accountable review instead of silently overwriting them.", "Keep ownership, next action, and verified outcome visible across organizational boundaries."]
},
requests: {
chapter: "Chapter 3",
title: "Treat intake as a care interaction",
items: ["Collect the minimum information needed for the next safe decision.", "Explain sensitive questions, recommendations, reasons, and accountable overrides.", "Use progressive disclosure and preserve contextual consent throughout intake."]
},
providers: {
chapter: "Chapter 6",
title: "Distinguish capability from confirmed inventory",
items: ["Provider profiles describe capability; unit records describe specific places and states.", "Match the complete date range and functional accessibility needs, not only aggregate capacity.", "Treat freshness, supporting services, rate terms, and provider confirmation as match evidence."]
},
availability: {
chapter: "Chapter 6",
title: "Make inventory state explicit and conflict-safe",
items: ["A hold needs an owner, acknowledgment, expiration, and release or conversion event.", "Reconcile aggregate capacity with unit-level state and declare the grain of each value.", "Do not treat a local inventory change as shared capacity until synchronization is confirmed."]
},
cases: {
chapter: "Chapter 7",
title: "Manage the decision chain, not one status",
items: ["Track accountable owner, response clock, next action, and return path for every case.", "Keep funding, provider acceptance, reservation, acknowledgment, stay, and finance states distinct.", "Close only with a verified service outcome and reconciled open exceptions."]
},
placement: {
chapter: "Chapter 7",
title: "Serialize each placement decision with evidence",
items: ["Create focused, versioned events with stable request, case, veteran, provider, and placement references.", "Use the unified timeline as the coordination spine for decisions, failures, and next actions.", "Distinguish local persistence, remote submission, and shared acceptance at every step."]
},
partnerOperations: {
chapter: "Chapter 8",
title: "Close the loop before transferring responsibility",
items: ["Sent, delivered, acknowledged, accepted, and completed are different operational states.", "Keep the sender accountable until ownership is accepted or reassigned through policy.", "Require work-type-specific closure evidence, accessible channels, and protective escalation paths."]
},
veterans: {
chapter: "Chapter 4",
title: "Provide continuity without creating an oversized record",
items: ["Show source, effective time, verification state, and owning record for summary values.", "Preserve duplicate-review evidence, reversibility, provenance, and correction history.", "Use consent and minimum-necessary access to govern what each participant can see."]
},
coordinatedEntry: {
chapter: "Chapter 5",
title: "Make prioritization explainable and correctable",
items: ["Show score inputs, rules, missing-data handling, reasons, limits, and rule version.", "Connect priority to an owner, response clock, and reassessment trigger.", "Preserve authorized overrides and review outcomes for fairness and learning."]
},
consent: {
chapter: "Chapter 5",
title: "Treat consent as contextual permission",
items: ["Validate person, recipient, information, purpose, effective period, and current status.", "Design minimum-necessary disclosure into each referral or handoff package.", "Preserve detailed disclosure and revocation events without erasing prior lawful activity."]
},
reports: {
chapter: "Chapter 10",
title: "Measure decisions and outcomes, not convenient fields",
items: ["Declare metric grain, denominator, exclusions, observation count, source, owner, and definition version.", "Use distributions and aging alongside averages to reveal hidden delays.", "Pair performance results with equity, dignity, data-quality, and synchronization guardrails."]
},
versionHistory: {
chapter: "Chapters 9, 11-12",
title: "Promote evidence, not feature lists",
items: ["Keep local save, remote send, remote acceptance, and version conflict states honest and traceable.", "Treat identity, authorization, privacy, accessibility, resilience, audit, and staffed operations as release requirements.", "Advance through governed vertical slices, operational simulations, controlled pilots, and explicit stop conditions."]
},
serviceOperations: {
chapter: "Chapters 10-12",
title: "Operate readiness as a continuous product capability",
items: ["Connect technical health to care impact, accountable ownership, and recovery targets.", "Test accessibility, concurrency, interruption, migration, tenant isolation, and rollback according to risk.", "Promote only when data quality, security, support, resilience, and controlled-pilot evidence meet explicit gates."]
},
assurance: {
chapter: "Chapters 1-12",
title: "Turn reflection into owned implementation evidence",
items: ["Keep all 102 controls traceable to an owner, status, evidence source, and verification method.", "Separate prototype evidence, remaining action, and external production capability honestly.", "Use the register as a living stage-gate artifact rather than a one-time checklist."]
}
};
const takeaway = takeaways[pageKey];
if (!takeaway || !pageContent) return;
const section = document.createElement("section");
section.className = "section-card";
section.dataset.pdfTakeaways = pageKey;
section.innerHTML = `
Book-aligned operating takeaways - ${escapeHtml(takeaway.chapter)} ${escapeHtml(takeaway.title)} Apply these safeguards while reviewing, creating, or changing records in this workspace.
Practice guidance
${takeaway.items.map((item, index) => `
${index + 1} ${escapeHtml(item)}
`).join("")}
`;
pageContent.append(section);
}
function redirectToLogin() {
const loginUrl = document.body.dataset.loginUrl;
if (loginUrl && !loginUrl.startsWith("__")) {
window.location.replace(loginUrl);
return;
}
pageContent.innerHTML = `Sign-in link unavailable Publish the page set to resolve the hosted login URL.
`;
}
function renderProfileChrome() {
document.querySelectorAll("[data-profile-name]").forEach((element) => {
element.textContent = activeProfile.displayName;
});
document.querySelectorAll("[data-profile-id]").forEach((element) => {
element.textContent = activeProfile.profileId;
element.title = `${activeProfile.role} | ${activeProfile.organization}`;
});
document.querySelectorAll("[data-profile-initials]").forEach((element) => {
element.textContent = profileManager.getInitials(activeProfile);
});
}
async function renderLogin() {
const savedProfiles = profileManager.getProfiles();
const currentProfile = profileManager.getActiveProfile();
const homeUrl = document.body.dataset.homeUrl;
if (currentProfile && homeUrl && !homeUrl.startsWith("__")) {
window.location.replace(homeUrl);
return;
}
pageContent.innerHTML = `
BeaReponseCare
Move every veteran request toward a safe, accountable placement.
BeaReponseCare is a connected care-coordination workspace for South Jersey teams managing urgent housing needs. It brings intake, eligibility, provider capacity, explainable matching, approvals, stay monitoring, consent, and outcomes into one operational view.
From urgent request to stable housing
One shared workflow, with the veteran and the next responsible action kept visible.
01 Capture Guided intake and eligibility
02 Match Provider fit and availability
03 Place Approval, reservation, and stay
04 Improve Outcomes, KPIs, and assurance
Connected records preserve context across veteran, request, case, provider, unit, placement, consent, and reporting workflows.
Product documentation
See how connected care becomes coordinated action.
Follow the complete journey from veteran intake and explainable matching through placement, stay monitoring, and measurable outcomes.
Learn how local-first continuity, accountable handoffs, and operational safeguards help teams act faster without losing context.
View documentation
16:39
Product walkthrough
See an urgent request become a coordinated placement.
The demonstration follows local profile setup, South Jersey intake, explainable provider matching, approvals, stay and funding updates, connected case records, and operational reporting.
Play walkthrough
Enter the care operations workspace
Create or resume a profile
This demonstration uses browser-local access. It supports workspace continuity but does not prove identity, organization membership, or authorization and does not send credentials to an identity provider.
Local-first takeaway: local save, remote send, and shared acceptance are separate states. Production access requires authenticated identity and server-enforced permission.
${savedProfiles.length ? `
Saved local profile
Select a saved profile
${savedProfiles.map((profile) => `${escapeHtml(profile.displayName)} - ${escapeHtml(profile.profileId)} `).join("")}
Resume
` : ""}
Select Play to load the walkthrough.
This 16:39 demonstration covers profile setup, cache refresh, guided intake, placement matching, provider and case coordination, editable connected records, and management reporting.
`;
bindLoginActions();
bindLoginVideo();
const loginParams = new URLSearchParams(window.location.search);
if (loginParams.get("localDataCleared") === "1") {
showToast("Local data cleared", "All BeaReponseCare browser data was removed. Sign in to create a new local profile.", "success");
window.history.replaceState(null, "", window.location.pathname);
} else if (loginParams.get("sessionExpired") === "1") {
showToast("Session expired", "The 30-minute inactivity limit was reached. Sign in again to continue.", "warning");
window.history.replaceState(null, "", window.location.pathname);
}
}
function bindLoginActions() {
const form = document.getElementById("localLoginForm");
const prefillButton = document.getElementById("prefillLoginButton");
const resumeButton = document.getElementById("resumeProfileButton");
const savedProfileSelect = document.getElementById("savedProfileSelect");
if (prefillButton) {
prefillButton.addEventListener("click", () => {
form.elements.displayName.value = "Jordan Ellis";
form.elements.email.value = "jordan.ellis@example.org";
form.elements.organization.value = "BeaReponseCare Operations";
form.elements.role.value = "System Administrator";
form.elements.region.value = "Camden County";
form.elements.workspaceCode.value = "BRC-DEMO-2026";
showToast("Example loaded", "The login form was prefilled. Review the fields before continuing.", "info");
});
}
if (resumeButton && savedProfileSelect) {
resumeButton.addEventListener("click", async () => {
try {
const profile = profileManager.activate(savedProfileSelect.value);
if (!profile) {
showToast("Profile required", "Select a saved local profile to continue.", "danger");
return;
}
showToast("Profile resumed", `Opening ${profile.profileId}.`, "success");
await storageService.flush();
window.location.href = document.body.dataset.homeUrl;
} catch (error) {
console.error("Profile resume failed", error);
showToast("Resume failed", "This browser could not activate the saved local profile.", "danger");
}
});
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (!form.reportValidity()) {
showToast("Validation required", "Complete the login fields before continuing.", "danger");
return;
}
showToast("Creating profile", "Generating a local profile ID for this workspace.", "primary");
const values = Object.fromEntries(new FormData(form).entries());
delete values.workspaceCode;
try {
const profile = profileManager.login(values);
showToast("Profile ready", `${profile.profileId} was created and activated.`, "success");
await storageService.flush();
window.location.href = document.body.dataset.homeUrl;
} catch (error) {
console.error("Profile creation failed", error);
showToast("Profile not saved", "This browser could not save the local profile. Check storage permissions and try again.", "danger");
}
});
}
function bindLoginVideo() {
const modalElement = document.getElementById("loginVideoModal");
const frame = modalElement?.querySelector("[data-login-video-frame]");
if (!modalElement || !frame || !window.bootstrap) {
return;
}
const videoModal = window.bootstrap.Modal.getOrCreateInstance(modalElement);
const loadVideo = () => {
frame.innerHTML = ``;
videoModal.show();
showToast("Walkthrough opened", "The BeaReponseCare product demonstration is ready to play.", "info");
};
document.querySelectorAll("[data-login-video-launch]").forEach((button) => button.addEventListener("click", loadVideo));
modalElement.querySelectorAll("[data-bs-dismiss='modal']").forEach((button) => {
button.addEventListener("click", () => videoModal.hide());
});
modalElement.addEventListener("hidden.bs.modal", () => {
frame.innerHTML = 'Select Play to load the walkthrough.
';
});
}
function showLoadingState() {
pageContent.innerHTML = `
Loading hosted records
Fetching the latest published JSON feeds
This page reads the live Xenhey read URLs and renders the results in scrollable tables.
`;
}
async function fetchDataset(key, options = {}) {
const forceRefresh = options.forceRefresh === true;
const sessionKey = `dataset:${dataCacheVersion}:${key}`;
if (forceRefresh && pendingDatasets[key]) {
await pendingDatasets[key].catch(() => null);
}
if (forceRefresh) {
delete tableStore[key];
storageService.removeSession(sessionKey);
}
if (tableStore[key]) {
return tableStore[key];
}
if (pendingDatasets[key]) {
return pendingDatasets[key];
}
const url = dataUrls[key];
if (!url || url.startsWith("__")) {
throw new Error(`Missing data URL for ${key}`);
}
const cached = storageService.readSession(sessionKey, null);
if (cached) {
tableStore[key] = cached;
return cached;
}
pendingDatasets[key] = apiService.getJson(url, { forceRefresh })
.then((data) => {
tableStore[key] = data;
try {
storageService.writeSession(sessionKey, data);
} catch (error) {
console.warn(`Session cache write failed for ${key}`, error);
}
return data;
})
.finally(() => {
delete pendingDatasets[key];
});
return pendingDatasets[key];
}
function injectSharedStyles() {
if (document.getElementById("brc-shared-styles")) {
return;
}
const style = document.createElement("style");
style.id = "brc-shared-styles";
style.textContent = `
.login-stage { position: relative; min-height: 100vh; overflow: hidden; display: grid; place-items: center; padding: clamp(1rem, 4vw, 4rem); background: linear-gradient(135deg, #07182f 0%, #0f315d 48%, #0b7188 100%); }
.login-atmosphere { position: absolute; inset: 0; pointer-events: none; background: radial-gradient(circle at 12% 18%, rgba(63, 146, 255, 0.42), transparent 28%), radial-gradient(circle at 86% 78%, rgba(34, 211, 238, 0.3), transparent 32%), repeating-linear-gradient(120deg, rgba(255,255,255,0.035) 0, rgba(255,255,255,0.035) 1px, transparent 1px, transparent 28px); }
.login-shell { position: relative; width: min(1120px, 100%); display: grid; grid-template-columns: minmax(0, 1fr) minmax(360px, 0.82fr); border: 1px solid rgba(255,255,255,0.18); border-radius: 2rem; overflow: hidden; box-shadow: 0 42px 90px -42px rgba(0,0,0,0.78); }
.login-story { display: flex; flex-direction: column; justify-content: center; padding: clamp(2rem, 5vw, 4.5rem); color: #fff; background: linear-gradient(145deg, rgba(7,24,47,0.96), rgba(15,49,93,0.78)); }
.login-story h1 { max-width: 720px; margin: 0.8rem 0 1rem; font-family: "Epilogue", sans-serif; font-size: clamp(2.2rem, 4.5vw, 4.4rem); line-height: 1.02; }
.login-story > p { max-width: 680px; color: rgba(235,245,255,0.78); font-size: 1.02rem; }
.login-product-lead { line-height: 1.72; }
.login-product-summary { margin-top: 1.35rem; padding: 1.15rem; border: 1px solid rgba(103,232,249,0.24); border-radius: 1.25rem; background: linear-gradient(135deg, rgba(29,94,255,0.16), rgba(15,49,93,0.38)); box-shadow: inset 0 1px 0 rgba(255,255,255,0.08); }
.login-documentation-panel { margin-top: 1rem; padding: 1.15rem; border: 1px solid rgba(255,255,255,0.16); border-radius: 1.2rem; background: rgba(5,27,59,0.52); }
.login-documentation-panel p { max-width: 58rem; color: rgba(255,255,255,0.78); }
.login-summary-intro { display: grid; gap: 0.4rem; }
.login-summary-intro strong { max-width: 620px; font-family: "Epilogue", sans-serif; font-size: clamp(1rem, 2vw, 1.2rem); line-height: 1.4; }
.login-journey { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.55rem; margin: 1rem 0 0; padding: 0; list-style: none; }
.login-journey li { min-width: 0; padding: 0.75rem; border-radius: 0.9rem; background: rgba(255,255,255,0.07); }
.login-journey span { display: block; margin-bottom: 0.3rem; color: #67e8f9; font-size: 0.68rem; font-weight: 800; letter-spacing: 0.12em; }
.login-journey strong, .login-journey small { display: block; }
.login-journey strong { font-size: 0.86rem; }
.login-journey small { margin-top: 0.22rem; color: rgba(235,245,255,0.68); font-size: 0.68rem; line-height: 1.35; }
.login-summary-note { display: flex; gap: 0.5rem; align-items: flex-start; margin: 0.85rem 0 0; color: rgba(235,245,255,0.76); font-size: 0.76rem; line-height: 1.5; }
.login-summary-note i { color: #67e8f9; font-size: 1rem; }
.login-video-panel { display: grid; grid-template-columns: minmax(150px, 0.82fr) minmax(0, 1.18fr); gap: 1rem; align-items: center; margin-top: 1.5rem; padding: 0.8rem; border: 1px solid rgba(255,255,255,0.14); border-radius: 1.2rem; background: rgba(255,255,255,0.07); }
.login-video-preview { position: relative; display: block; width: 100%; padding: 0; aspect-ratio: 16 / 9; overflow: hidden; border: 1px solid rgba(255,255,255,0.2); border-radius: 0.9rem; background: #07182f; color: #fff; box-shadow: 0 18px 34px -24px rgba(0,0,0,0.88); }
.login-video-preview::after { content: ""; position: absolute; inset: 0; background: linear-gradient(180deg, transparent 38%, rgba(7,24,47,0.76)); }
.login-video-preview img { width: 100%; height: 100%; object-fit: cover; transition: transform 240ms ease; }
.login-video-preview:hover img, .login-video-preview:focus-visible img { transform: scale(1.035); }
.login-video-preview:focus-visible { outline: 3px solid #67e8f9; outline-offset: 3px; }
.login-video-play { position: absolute; z-index: 1; top: 50%; left: 50%; display: grid; width: 3.2rem; height: 3.2rem; place-items: center; border-radius: 999px; transform: translate(-50%, -50%); background: rgba(29,94,255,0.94); box-shadow: 0 12px 24px rgba(0,0,0,0.35); font-size: 1.55rem; }
.login-video-duration { position: absolute; z-index: 1; right: 0.55rem; bottom: 0.45rem; padding: 0.18rem 0.4rem; border-radius: 0.35rem; background: rgba(7,24,47,0.84); font-size: 0.68rem; font-weight: 800; }
.login-video-copy h2 { margin: 0.3rem 0 0.35rem; color: #fff; font-family: "Epilogue", sans-serif; font-size: 1rem; line-height: 1.3; }
.login-video-copy p { margin-bottom: 0.7rem; color: rgba(235,245,255,0.74); font-size: 0.78rem; line-height: 1.5; }
.login-video-modal-content { border: 0; border-radius: 1.4rem; overflow: hidden; }
.login-video-frame { overflow: hidden; border-radius: 1rem; background: #07182f; }
.login-video-frame iframe { border: 0; }
.login-card { padding: clamp(1.5rem, 4vw, 3rem); background: rgba(255,255,255,0.98); }
.login-card .form-control, .login-card .form-select { min-height: 48px; border-radius: 0.9rem; }
.saved-profile-panel { padding: 1rem; border-radius: 1rem; background: rgba(29,94,255,0.06); border: 1px solid rgba(29,94,255,0.12); }
.local-record-badge { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.28rem 0.55rem; border-radius: 999px; background: #dcfce7; color: #15803d; font-size: 0.72rem; font-weight: 700; }
.linked-record-panel { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; padding: 1rem; border-radius: 1rem; background: rgba(29, 94, 255, 0.06); border: 1px solid rgba(29, 94, 255, 0.14); }
[data-record-workspace] { min-width: 0; }
.record-workspace-tabs { flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; padding-bottom: 0.2rem; scroll-behavior: smooth; scroll-snap-type: x proximity; scrollbar-width: thin; }
.record-workspace-tabs .nav-item { flex: 0 0 auto; scroll-snap-align: start; }
.record-workspace-tabs .nav-link { white-space: nowrap; }
.record-workspace-tabs [data-dynamic-edit-tab] .nav-link { padding-right: 2.6rem; }
.record-workspace-tabs .edit-tab-close { z-index: 2; color: #64748b; }
.record-workspace-tabs .edit-tab-close:hover, .record-workspace-tabs .edit-tab-close:focus-visible { color: #b42318; background: rgba(180, 35, 24, 0.08); }
.modal-typeahead { position: relative; min-width: 0; }
.modal-typeahead-source { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; margin: -1px !important; overflow: hidden !important; clip: rect(0, 0, 0, 0) !important; white-space: nowrap !important; border: 0 !important; }
.modal-typeahead-input { padding-right: 2.4rem; background-image: none; }
.modal-typeahead-toggle { position: absolute; top: 0; right: 0; height: 100%; width: 2.4rem; border: 0; background: transparent; color: #64748b; }
.modal-typeahead-menu { position: fixed; z-index: 1095; display: none; max-height: min(18rem, 45vh); overflow-y: auto; padding: 0.35rem; border: 1px solid rgba(148, 163, 184, 0.36); border-radius: 0.8rem; background: #fff; box-shadow: 0 20px 38px -22px rgba(15, 23, 42, 0.72); }
.modal-typeahead-menu.show { display: block; }
.modal-typeahead-option { width: 100%; padding: 0.55rem 0.65rem; border: 0; border-radius: 0.55rem; background: transparent; color: #132033; text-align: left; overflow-wrap: anywhere; }
.modal-typeahead-option:hover, .modal-typeahead-option:focus, .modal-typeahead-option.active { color: #123fbd; background: rgba(29, 94, 255, 0.1); outline: 0; }
.modal-typeahead-empty { padding: 0.65rem; color: #64748b; font-size: 0.85rem; }
.table-search-typeahead { position: relative; min-width: min(100%, 18rem); }
.table-search-menu { position: absolute; z-index: 1090; top: calc(100% + 0.3rem); right: 0; left: 0; display: none; max-height: min(20rem, 45vh); overflow-y: auto; padding: 0.35rem; border: 1px solid rgba(148, 163, 184, 0.36); border-radius: 0.8rem; background: #fff; box-shadow: 0 20px 38px -22px rgba(15, 23, 42, 0.72); }
.table-search-menu.show { display: block; }
.table-search-option { width: 100%; display: grid; gap: 0.15rem; padding: 0.6rem 0.7rem; border: 0; border-radius: 0.6rem; background: transparent; color: #132033; text-align: left; }
.table-search-option:hover, .table-search-option:focus, .table-search-option.active { color: #123fbd; background: rgba(29, 94, 255, 0.1); outline: 0; }
.table-search-option strong { font-size: 0.84rem; overflow-wrap: anywhere; }
.table-search-option span, .table-search-empty { color: #64748b; font-size: 0.76rem; overflow-wrap: anywhere; }
.table-search-empty { padding: 0.65rem; }
.placement-search-menu { position: fixed; z-index: 1090; display: none; max-height: min(24rem, 55vh); overflow-y: auto; padding: 0.45rem; border: 1px solid rgba(148, 163, 184, 0.36); border-radius: 1rem; background: #fff; box-shadow: 0 24px 48px -24px rgba(15, 23, 42, 0.72); }
.placement-search-menu.show { display: block; }
.placement-search-option { width: 100%; display: grid; gap: 0.2rem; padding: 0.7rem 0.8rem; border: 0; border-radius: 0.75rem; background: transparent; color: #132033; text-align: left; }
.placement-search-option:hover, .placement-search-option:focus, .placement-search-option.active { color: #123fbd; background: rgba(29, 94, 255, 0.1); outline: 0; }
.placement-search-option strong { font-size: 0.9rem; }
.placement-search-option span { color: #64748b; font-size: 0.76rem; overflow-wrap: anywhere; }
.placement-search-empty { padding: 0.8rem; color: #64748b; font-size: 0.85rem; }
.placement-search-toolbar { display: flex; flex: 1 1 30rem; align-items: center; gap: 0.55rem; min-width: min(100%, 240px); }
.placement-search-toolbar .search-shell { flex: 1 1 auto; width: auto; min-width: 0; }
.placement-refresh-button { display: inline-grid; width: 50px; height: 50px; flex: 0 0 50px; place-items: center; padding: 0; border: 1px solid rgba(148, 163, 184, 0.3); border-radius: 1rem; color: #1d5eff; background: rgba(248, 250, 252, 0.96); }
.placement-refresh-button:hover, .placement-refresh-button:focus-visible { color: #fff; background: #1d5eff; border-color: #1d5eff; }
.placement-refresh-button:disabled { color: #64748b; background: #eef2f7; }
.demo-disclosure { border-left: 4px solid #d7a34a; background: linear-gradient(135deg, rgba(255, 248, 225, 0.96), rgba(255, 255, 255, 0.96)); }
.workflow-tabs { flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; scrollbar-width: thin; }
.workflow-tabs .nav-link { min-height: 100%; white-space: nowrap; font-weight: 700; }
.workflow-panel { padding: 1.1rem; border: 1px solid rgba(148, 163, 184, 0.22); border-radius: 1.2rem; background: rgba(248, 251, 255, 0.82); }
.workflow-action-bar { display: flex; justify-content: space-between; align-items: center; gap: 0.75rem; flex-wrap: wrap; padding-top: 1rem; }
.match-score { width: 3.2rem; height: 3.2rem; display: inline-grid; place-items: center; flex: 0 0 3.2rem; border-radius: 1rem; color: #fff; background: linear-gradient(135deg, #15803d, #22c55e); font-weight: 800; }
.activity-timeline { display: grid; gap: 0.75rem; max-height: 30rem; overflow-y: auto; }
.activity-entry { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 0.75rem; padding: 0.85rem; border-radius: 1rem; border: 1px solid rgba(148, 163, 184, 0.2); background: rgba(255, 255, 255, 0.92); }
.activity-entry-icon { width: 2.25rem; height: 2.25rem; display: inline-grid; place-items: center; border-radius: 0.75rem; color: #1d5eff; background: rgba(29, 94, 255, 0.1); }
.sla-clock { font-variant-numeric: tabular-nums; }
.connected-record-card { border: 1px solid rgba(148, 163, 184, 0.24); border-radius: 1.1rem; padding: 1rem; background: rgba(248, 251, 255, 0.78); }
.connected-record-card + .connected-record-card { margin-top: 1rem; }
.connected-table-tools { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: end; gap: 0.75rem; }
.connected-table-tools .form-control, .connected-table-tools .form-select { min-width: min(100%, 180px); }
.connected-table-scroll { max-height: 410px; overflow: auto; border: 1px solid rgba(148, 163, 184, 0.22); border-radius: 1rem; }
.connected-table-scroll table { min-width: 760px; margin-bottom: 0; }
.connected-table-scroll thead { position: sticky; top: 0; z-index: 2; }
.topbar > .d-flex:first-child, .topbar > .d-flex:first-child > div, .profile-chip > div { min-width: 0; }
.page-title, .profile-chip strong, .profile-chip small { overflow-wrap: anywhere; }
.search-shell .form-control { min-width: 0; }
.hero-panel, .section-card { background: rgba(255, 255, 255, 0.92); border: 1px solid rgba(255, 255, 255, 0.8); border-radius: 1.75rem; box-shadow: 0 28px 60px -32px rgba(12, 28, 63, 0.28); min-width: 0; }
.hero-panel { display: flex; justify-content: space-between; gap: 1.5rem; padding: 1.6rem; overflow: hidden; align-items: center; flex-wrap: wrap; background: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(245, 249, 255, 0.95)); min-width: 0; }
.hero-copy { max-width: 720px; min-width: 0; flex: 1 1 420px; }
.hero-panel h2, .story-card h3, .section-card h3, .modal-title { font-family: "Epilogue", sans-serif; }
.hero-panel h2 { font-size: clamp(1.9rem, 2.5vw, 3rem); margin-bottom: 0.8rem; }
.hero-art { min-width: 0; width: min(100%, 360px); max-width: 100%; flex: 1 1 280px; padding: 1.25rem; border-radius: 1.4rem; background: linear-gradient(135deg, rgba(12, 28, 63, 0.04), rgba(29, 94, 255, 0.12)), #fff; border: 1px solid rgba(148, 163, 184, 0.2); }
.mini-stat { padding: 0.95rem 1rem; border-radius: 1rem; background: rgba(255, 255, 255, 0.96); border: 1px solid rgba(148, 163, 184, 0.18); margin-bottom: 0.75rem; }
.metric-grid, .story-grid, .timeline-grid, .insight-grid { display: grid; gap: 1rem; }
.metric-grid { grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); }
.metric-card { display: flex; gap: 1rem; align-items: center; padding: 1.1rem 1.2rem; background: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(245, 249, 255, 0.95)); border-radius: 1.35rem; border: 1px solid rgba(148, 163, 184, 0.18); min-width: 0; }
.metric-card i { width: 3rem; height: 3rem; display: inline-flex; align-items: center; justify-content: center; border-radius: 1rem; color: #1d5eff; background: rgba(29, 94, 255, 0.12); font-size: 1.2rem; }
.metric-link-card { width: 100%; color: inherit; text-align: left; cursor: pointer; transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease; }
.metric-link-card:hover, .metric-link-card:focus-visible { transform: translateY(-2px); border-color: rgba(29, 94, 255, 0.42); box-shadow: 0 22px 34px -28px rgba(29, 94, 255, 0.75); outline: 0; }
.metric-link-card .metric-link-arrow { width: auto; height: auto; margin-left: auto; background: transparent; color: #1d5eff; }
.section-card { padding: 1.35rem; background: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(248, 251, 255, 0.95)); overflow: hidden; }
.story-grid { grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }
.story-card { display: flex; gap: 1rem; align-items: flex-start; padding: 1rem; border-radius: 1.2rem; background: rgba(248, 251, 255, 0.96); border: 1px solid rgba(148, 163, 184, 0.18); height: 100%; min-width: 0; }
.story-card .icon-shell, .flow-chip { width: 3rem; height: 3rem; display: inline-flex; align-items: center; justify-content: center; border-radius: 1rem; color: #fff; background: linear-gradient(135deg, #1d5eff, #19a8c9); }
.workflow-linkage { display: flex; align-items: center; gap: 0.65rem; overflow-x: auto; padding: 0.35rem 0 0.75rem; }
.workflow-link-stage { display: grid; gap: 0.65rem; min-width: 10.5rem; }
.workflow-link-node { display: flex; align-items: center; gap: 0.7rem; width: 100%; min-height: 4.6rem; padding: 0.8rem; text-align: left; color: #172a43; background: #eef5ff; border: 1px solid #7aa7ff; border-radius: 0.9rem; }
.workflow-link-node:hover, .workflow-link-node:focus-visible { border-color: #1d5eff; box-shadow: 0 12px 24px -18px rgba(29,94,255,0.8); outline: 0; }
.workflow-link-node > i { color: #1d5eff; font-size: 1.15rem; }
.workflow-link-node strong, .workflow-link-node small { display: block; overflow-wrap: anywhere; }
.workflow-link-node small { margin-top: 0.15rem; color: #64748b; }
.workflow-link-arrow { flex: 0 0 auto; color: #64748b; font-size: 1.2rem; }
.table-tools, .cta-strip, .page-shell { display: flex; justify-content: space-between; gap: 0.85rem; flex-wrap: wrap; align-items: center; }
.table-tools .filters { display: flex; gap: 0.75rem; flex-wrap: wrap; }
.table-summary { display: flex; gap: 0.6rem; flex-wrap: wrap; align-items: center; margin-top: 0.55rem; }
.table-summary-chip { display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.42rem 0.72rem; border-radius: 999px; background: rgba(29, 94, 255, 0.08); color: #1d4ed8; font-size: 0.8rem; font-weight: 700; }
.table-shell { border-radius: 1.4rem; border: 1px solid rgba(148, 163, 184, 0.18); overflow: hidden; background: rgba(255, 255, 255, 0.98); min-width: 0; }
.table-shell .table-responsive { max-height: 32rem; overflow: auto; -webkit-overflow-scrolling: touch; }
.table thead th { background: rgba(248, 250, 252, 0.94); color: #132033; font-weight: 700; }
.table-sort-btn { display: inline-flex; align-items: center; gap: 0.45rem; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; font-weight: 700; }
.table-sort-btn:hover { color: #1d5eff; }
.table-sort-btn .sort-icon { font-size: 0.8rem; color: #64748b; }
.table-sort-btn[aria-sort='ascending'] .sort-icon,
.table-sort-btn[aria-sort='descending'] .sort-icon { color: #1d5eff; }
.table > :not(caption) > * > * { padding: 0.9rem 1rem; white-space: nowrap; }
.table tbody td:nth-child(4), .table tbody td:nth-child(5), .table tbody td:nth-child(6), .table tbody td:nth-child(7), .table tbody td:nth-child(8) { max-width: 16rem; overflow: hidden; text-overflow: ellipsis; }
.table-dense { font-size: 0.82rem; line-height: 1.25; }
.table-dense > :not(caption) > * > * { padding: 0.55rem 0.65rem; vertical-align: middle; }
.table-dense tbody td { max-width: 12rem; white-space: normal; overflow-wrap: anywhere; }
.table-dense thead th { white-space: nowrap; }
.table-action-cell { position: sticky; left: 0; z-index: 2; width: 3.6rem; min-width: 3.6rem; max-width: 3.6rem !important; background: #fff; box-shadow: 1px 0 0 rgba(148, 163, 184, 0.22); text-align: center; }
.table-dense thead .table-action-cell { z-index: 4; background: #f8fafc; }
.table-context { min-width: 8.5rem; max-width: 11rem; }
.table-context-line { display: block; margin-top: 0.16rem; color: #64748b; font-size: 0.72rem; line-height: 1.25; }
.table-context-line:first-child { margin-top: 0; }
.status-pill, .priority-pill { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.38rem 0.7rem; border-radius: 999px; font-size: 0.78rem; font-weight: 700; }
.priority-pill.critical, .status-pill.critical { background: #fee2e2; color: #b91c1c; }
.priority-pill.high, .status-pill.high { background: #fef3c7; color: #b45309; }
.priority-pill.medium, .status-pill.medium { background: #dbeafe; color: #1d4ed8; }
.priority-pill.low, .status-pill.low { background: #dcfce7; color: #15803d; }
.timeline-grid { grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); }
.timeline-card { padding: 1rem; border-radius: 1.2rem; border: 1px solid rgba(148, 163, 184, 0.18); background: linear-gradient(180deg, #fff 0%, #f8fbff 100%); height: 100%; min-width: 0; }
.timeline-step { display: flex; gap: 0.85rem; align-items: flex-start; padding-top: 0.9rem; border-top: 1px solid rgba(15, 23, 42, 0.08); margin-top: 0.9rem; }
.step-dot { width: 0.9rem; height: 0.9rem; border-radius: 50%; margin-top: 0.25rem; background: linear-gradient(135deg, #1d5eff, #19a8c9); flex: 0 0 auto; }
.timeline-meta, .mini-label { letter-spacing: 0.08em; text-transform: uppercase; font-size: 0.72rem; }
.insight-grid { grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); }
.insight-card, .flow-card { border-radius: 1.15rem; padding: 1rem; background: rgba(255, 255, 255, 0.98); border: 1px solid rgba(148, 163, 184, 0.18); min-width: 0; }
.form-preview { min-height: 180px; padding: 1rem; border-radius: 1rem; background: #0f172a; color: #dbeafe; font-size: 0.88rem; white-space: pre-wrap; overflow-wrap: anywhere; }
.quick-actions { display: flex; gap: 0.75rem; flex-wrap: wrap; }
.cta-strip { padding: 1rem 1.2rem; border-radius: 1.25rem; background: linear-gradient(135deg, rgba(29, 94, 255, 0.08), rgba(25, 168, 201, 0.12)); border: 1px solid rgba(29, 94, 255, 0.12); min-width: 0; }
.flow-chip { width: 2.75rem; height: 2.75rem; flex: 0 0 auto; font-size: 1rem; }
.source-note { font-size: 0.85rem; color: #475569; }
.doc-toolbar { display: flex; gap: 0.75rem; flex-wrap: wrap; margin-top: 1rem; }
.contract-doc-grid { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); }
.contract-doc-card { border-radius: 1.2rem; border: 1px solid rgba(148, 163, 184, 0.18); background: rgba(255, 255, 255, 0.98); padding: 1rem; min-width: 0; }
.contract-doc-card p:last-child { margin-bottom: 0; }
.contract-doc-body { color: #1e293b; overflow-wrap: anywhere; }
.contract-doc-body h2,
.contract-doc-body h3,
.contract-doc-body h4,
.contract-doc-body h5 { font-family: "Epilogue", sans-serif; margin-top: 1rem; margin-bottom: 0.65rem; }
.contract-doc-body h2:first-child,
.contract-doc-body h3:first-child { margin-top: 0; }
.contract-doc-body ul,
.contract-doc-body ol { padding-left: 1.2rem; }
.contract-doc-body code { padding: 0.08rem 0.36rem; border-radius: 0.35rem; background: rgba(29, 94, 255, 0.08); color: #1d4ed8; }
.contract-doc-table th { white-space: nowrap; }
.accordion.contract-doc-accordion { --bs-accordion-border-color: rgba(148, 163, 184, 0.18); --bs-accordion-btn-focus-box-shadow: 0 0 0 0.2rem rgba(29, 94, 255, 0.12); --bs-accordion-active-bg: rgba(29, 94, 255, 0.08); --bs-accordion-active-color: #1d4ed8; }
.accordion.contract-doc-accordion .accordion-item { border-radius: 1rem; overflow: hidden; }
.accordion.contract-doc-accordion .accordion-button { font-weight: 700; }
.research-source-list { display: grid; gap: 0.75rem; }
.research-source-item { padding: 0.95rem 1rem; border-radius: 1rem; border: 1px solid rgba(148, 163, 184, 0.18); background: rgba(248, 251, 255, 0.96); }
.modal-record-form .form-label { font-size: 0.82rem; text-transform: uppercase; letter-spacing: 0.08em; color: #475569; font-weight: 700; }
.modal-record-form .form-control,
.modal-record-form .form-select { border-radius: 0.95rem; border-color: rgba(148, 163, 184, 0.28); }
.modal-record-form .form-control:focus,
.modal-record-form .form-select:focus { box-shadow: 0 0 0 0.2rem rgba(29, 94, 255, 0.14); border-color: rgba(29, 94, 255, 0.45); }
.modal-record-form .field-card { border: 1px solid rgba(148, 163, 184, 0.18); border-radius: 1rem; padding: 0.9rem; background: rgba(248, 251, 255, 0.92); height: 100%; }
.modal-dialog:not(.modal-xl) { max-width: min(860px, calc(100vw - 1.5rem)); }
.modal-dialog.modal-xl { width: min(1280px, calc(100vw - 2rem)); max-width: min(1280px, calc(100vw - 2rem)); }
.modal-dialog-scrollable .modal-content { max-height: calc(100vh - 2rem); }
.modal-body { overflow-x: hidden; }
.modal-body .row > [class*='col-'] { min-width: 0; }
body.modal-open #toastStack { bottom: 5.75rem !important; max-width: min(360px, calc(100vw - 1.5rem)); }
.text-break-mobile { overflow-wrap: anywhere; }
@media (max-width: 991.98px) {
.login-shell { grid-template-columns: 1fr; }
.login-story { padding: 2rem; }
.login-story h1 { font-size: clamp(2rem, 7vw, 3.3rem); }
.hero-panel {
flex-direction: column;
padding: 1.15rem;
}
.hero-art,
.hero-copy,
.story-card,
.metric-card,
.timeline-card,
.insight-card,
.flow-card {
width: 100%;
}
.section-card,
.portal-content {
padding: 1rem;
}
.quick-actions > .btn,
.page-shell > .quick-actions,
.cta-strip > .btn {
width: 100%;
}
.topbar > .d-flex:first-child { width: 100%; }
.topbar-actions > [data-action="notifications"] { width: 3rem; flex: 0 0 3rem; }
.metric-grid,
.story-grid,
.timeline-grid,
.insight-grid,
.flow-grid {
grid-template-columns: 1fr;
}
.table-tools,
.table-tools .filters,
.page-shell,
.cta-strip {
flex-direction: column;
align-items: stretch;
}
.table-tools .filters > * {
width: 100%;
}
.table-shell .table-responsive {
max-height: 24rem;
}
.workflow-linkage { flex-direction: column; align-items: stretch; overflow: visible; }
.workflow-link-stage { width: 100%; min-width: 0; }
.workflow-link-arrow { align-self: center; transform: rotate(90deg); }
.table > :not(caption) > * > * {
padding: 0.8rem 0.75rem;
}
.modal-dialog {
margin: 0.75rem;
}
.modal-dialog.modal-xl {
width: calc(100vw - 1.5rem);
max-width: calc(100vw - 1.5rem);
}
.modal-content {
border-radius: 1.25rem;
}
.form-preview {
font-size: 0.82rem;
}
}
@media (max-width: 575.98px) {
.login-stage { padding: 0; place-items: stretch; }
.login-shell { min-height: 100vh; border: 0; border-radius: 0; }
.login-story, .login-card { padding: 1.25rem; }
.login-journey { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.login-video-panel { grid-template-columns: 1fr; }
.login-documentation-panel .btn { width: 100%; }
.hero-panel,
.section-card {
border-radius: 1.25rem;
}
.hero-panel {
gap: 1rem;
padding: 1rem;
}
.hero-panel h2 {
font-size: 1.55rem;
}
.hero-art,
.metric-card,
.story-card,
.timeline-card,
.insight-card,
.flow-card,
.intake-pane,
.cta-strip {
border-radius: 1rem;
}
.section-card,
.portal-content {
padding: 0.9rem;
}
.metric-card,
.story-card,
.timeline-card,
.insight-card,
.flow-card,
.intake-pane {
padding: 0.9rem;
}
.metric-card {
align-items: flex-start;
}
.metric-card i,
.story-card .icon-shell,
.flow-chip {
width: 2.65rem;
height: 2.65rem;
}
.table-tools .filters {
gap: 0.6rem;
}
.table-tools .filters label,
.table-tools .filters .d-flex {
width: 100%;
}
.table-summary {
width: 100%;
}
.table-shell .table-responsive {
max-height: 20rem;
}
.modal-dialog {
width: 100%;
height: 100%;
margin: 0;
max-width: 100%;
}
.modal-dialog.modal-xl {
width: 100%;
max-width: 100%;
}
.modal-dialog-scrollable .modal-content {
height: 100%;
max-height: 100%;
border: 0;
border-radius: 0;
}
.modal-header,
.modal-body,
.modal-footer {
padding-left: 0.95rem;
padding-right: 0.95rem;
}
.modal-footer {
gap: 0.6rem;
}
.modal-footer .btn {
width: 100%;
}
body.modal-open #toastStack {
right: 0.75rem !important;
bottom: 7.5rem !important;
left: 0.75rem !important;
max-width: none;
padding: 0 !important;
}
}
`;
document.head.appendChild(style);
}
function bindMobileSidebar() {
const mobileSidebar = document.getElementById("mobileSidebar");
if (!mobileSidebar || !window.bootstrap) {
return;
}
const offcanvas = window.bootstrap.Offcanvas.getOrCreateInstance(mobileSidebar);
const activeLink = mobileSidebar.querySelector(".nav-link.active");
if (activeLink) {
activeLink.setAttribute("aria-current", "page");
}
mobileSidebar.addEventListener("shown.bs.offcanvas", () => {
const currentActiveLink = mobileSidebar.querySelector(".nav-link.active");
if (currentActiveLink) {
currentActiveLink.scrollIntoView({ block: "nearest" });
}
});
document.querySelectorAll("#mobileSidebar .nav-link").forEach((link) => {
link.addEventListener("click", () => {
offcanvas.hide();
});
});
}
function bindFastNavigation() {
document.querySelectorAll("#mobileSidebar .nav-link[data-nav-key]").forEach((link) => {
link.addEventListener("click", (event) => {
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
return;
}
event.preventDefault();
navigateToPage(link.dataset.navKey, link.href);
});
});
}
async function navigateToPage(pageKey, href, options = {}) {
if (!pageDefinitions[pageKey]) {
window.location.href = href;
return;
}
if (!canAccessPage(pageKey)) {
showToast("Access restricted", `${activeProfile.role} is scoped to assigned workflows only.`, "danger");
return;
}
if (pageKey === currentPage && !options.fromHistory) {
window.scrollTo({ top: 0, behavior: "auto" });
return;
}
currentPage = pageKey;
activeDrilldown = options.drilldown || null;
updatePageChrome(pageKey);
if (!options.fromHistory) {
window.history.pushState({ brcPage: pageKey, drilldown: activeDrilldown }, "", href);
}
window.scrollTo({ top: 0, behavior: "auto" });
await renderPage(pageKey, { announce: options.announce !== false, href, drilldown: activeDrilldown });
}
function handleHistoryNavigation(event) {
const pageKey = event.state && event.state.brcPage;
if (!pageKey || !pageDefinitions[pageKey]) {
window.location.reload();
return;
}
navigateToPage(pageKey, window.location.href, { fromHistory: true, announce: false, drilldown: event.state.drilldown || readDrilldownFromUrl() });
}
function updatePageChrome(pageKey) {
const chrome = pageChrome[pageKey];
if (!chrome) {
return;
}
document.body.dataset.page = pageKey;
document.title = `${chrome.heading} | BeaReponseCare`;
setText("pageHeaderKicker", chrome.kicker);
setText("pageHeaderTitle", chrome.heading);
setText("quickAddButton", chrome.action);
setText("sidebarFooterKicker", chrome.footerKicker);
setText("sidebarFooterTitle", chrome.footerTitle);
setText("sidebarFooterNote", chrome.footerNote);
if (searchInput) {
searchInput.value = "";
searchInput.placeholder = chrome.search;
}
document.querySelectorAll("#mobileSidebar .nav-link[data-nav-key]").forEach((link) => {
const isActive = link.dataset.navKey === pageKey;
link.classList.toggle("active", isActive);
if (isActive) {
link.setAttribute("aria-current", "page");
} else {
link.removeAttribute("aria-current");
}
});
}
function setText(elementId, value) {
const element = document.getElementById(elementId);
if (element) {
element.textContent = value;
}
}
function warmNavigationAssets() {
document.querySelectorAll("#mobileSidebar .nav-link[data-nav-key]").forEach((link) => {
if (!link.href || link.href === window.location.href) {
return;
}
const prefetch = document.createElement("link");
prefetch.rel = "prefetch";
prefetch.as = "document";
prefetch.href = link.href;
document.head.appendChild(prefetch);
});
Object.keys(dataUrls).forEach((key) => {
fetchDataset(key).catch((error) => {
console.warn(`Background data warm failed for ${key}`, error);
});
});
}
function bindChromeActions() {
document.querySelectorAll("[data-action='notifications']").forEach((button) => {
button.addEventListener("click", () => {
modalState = null;
openRecordModal("Operational activity", `
Event history Local saves, role decisions, remote submissions, and failures are recorded for the active browser profile.
${renderActivityTimelineMarkup()}
`, "Activity reviewed");
modalPrimaryAction.textContent = "Close";
modalPrimaryAction.onclick = () => modalInstance?.hide();
});
});
document.querySelectorAll("[data-action='quick-add']").forEach((button) => {
button.addEventListener("click", () => {
if (currentPage === "versionHistory") {
document.querySelector("[data-current-release]")?.scrollIntoView({ behavior: "smooth", block: "center" });
showToast("Current version", "Version 0.11.0 is the active documented prototype build.", "info");
return;
}
if (currentPage === "serviceOperations") {
document.querySelector("[data-readiness-check]")?.click();
return;
}
const firstTable = pageContent.querySelector("table[data-filter-key]");
const firstTableId = firstTable ? firstTable.id : "";
if (!firstTableId) {
showToast("New record unavailable", "This page does not have a table ready for intake.", "info");
return;
}
openNewRecordEditor(firstTableId);
});
});
document.querySelectorAll("[data-action='profile']").forEach((button) => {
button.addEventListener("click", openProfileWorkspace);
});
document.querySelectorAll("[data-action='logout']").forEach((button) => {
button.addEventListener("click", async () => {
apiService?.clearCredential?.();
profileManager.logout();
showToast("Signed out", "The local profile remains saved and can be resumed from the landing page.", "success");
await storageService.flush();
window.location.href = document.body.dataset.loginUrl;
});
});
}
function openProfileWorkspace() {
modalState = null;
openRecordModal("Profile and local cache", renderProfileWorkspaceMarkup(), "Profile workspace opened");
bindProfileWorkspace();
}
function renderProfileWorkspaceMarkup() {
const roles = ["Care Operations", "Case Manager", "Coordinated Entry Assessor", "Consent Steward", "Inventory Coordinator", "Provider Success", "Program Analytics", "Government Programs", "System Administrator", "Proposal Manager"];
const regions = ["Atlantic County", "Burlington County", "Camden County", "Cape May County", "Cumberland County", "Gloucester County", "Salem County"];
const contacts = ["Email", "Phone", "SMS", "Secure message"];
const timezones = ["America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles"];
const languages = ["English", "Spanish", "French", "Vietnamese", "Tagalog"];
const options = (values, selectedValue) => values.map((value) => `${escapeHtml(value)} `).join("");
return `
Profile details
Local cache
Synchronization
${renderProfileCacheLists()}
Loading storage and synchronization evidence...
`;
}
function renderProfileCacheLists() {
const profileEntries = storageService.listProfileEntries(activeProfile.profileId);
const sessionEntries = storageService.listSessionEntries();
return `
Browser persistence
Checking IndexedDB, Cache Storage, and extension storage availability...
Checking
Refresh hosted data
Reload the latest published requests, providers, cases, and reports without removing your profile or local record changes.
Refresh all hosted data
Clear all BeaReponseCare local data
This removes every saved profile, local record, and cached dataset from this browser, then returns you to sign in.
Clear all local data and sign out
${renderCacheGroup("Profile-local changes", "Records added or edited under this profile.", "profile", profileEntries)}
${renderCacheGroup("Session datasets", "Hosted feeds cached for faster navigation in this browser tab.", "session", sessionEntries)}
`;
}
async function hydrateSyncWorkspace(container) {
if (!container || !activeProfile) return;
const boundedRead = (promise, label) => Promise.race([
promise,
new Promise((_, reject) => window.setTimeout(() => reject(new Error(`${label} did not respond within 4 seconds.`)), 4000))
]);
const results = await Promise.allSettled([
boundedRead(storageService.getStorageInventory(activeProfile.profileId), "Storage inventory"),
boundedRead(storageService.listDurable(activeProfile.profileId, "remote-queue"), "Submission queue"),
boundedRead(storageService.listDurable(activeProfile.profileId, "remote-receipts"), "Remote receipts"),
boundedRead(storageService.listDurable(activeProfile.profileId, "conflict-drafts"), "Conflict drafts")
]);
if (!container.isConnected) return;
const inventory = results[0].status === "fulfilled" ? results[0].value : [
{ layer: "Memory", contents: "Active page state and session-only remote credential", retention: "Until reload or sign out", count: null },
{ layer: "Memory cache", contents: "Published dataset cache", retention: "Current page session", count: storageService.listSessionEntries().length },
{ layer: storageService.supportsChromeExtensionStorage() ? "Chrome extension storage" : "IndexedDB application store", contents: "Local profile, drafts, additions, overrides, and activity index", retention: "Until user deletion", count: storageService.listProfileEntries(activeProfile.profileId).length },
{ layer: "IndexedDB", contents: "Durable records, queues, receipts, and conflict drafts", retention: "Inspection unavailable", count: "Unavailable" },
{ layer: "Cache Storage", contents: "Application-owned response caches only", retention: "Until application deletion", count: "Unavailable" },
{ layer: "Shared service", contents: "Submitted operation envelope and remote acknowledgement", retention: "Controlled by the remote service", count: null }
];
const queueEntries = results[1].status === "fulfilled" ? results[1].value : [];
const receiptEntries = results[2].status === "fulfilled" ? results[2].value : [];
const conflictEntries = results[3].status === "fulfilled" ? results[3].value : [];
const readFailures = results.map((result, index) => result.status === "rejected" ? ["Storage inventory", "Submission queue", "Remote receipts", "Conflict drafts"][index] : "").filter(Boolean);
const queues = queueEntries.map((entry) => entry.value);
const receipts = receiptEntries.map((entry) => entry.value);
container.innerHTML = `
${readFailures.length ? `Some browser storage could not be inspected. ${escapeHtml(readFailures.join(", "))}. Close other BeaReponseCare tabs if an IndexedDB upgrade is blocked.
Retry ` : ""}
Session-only credential boundary A reusable service credential is never embedded in hosted code or persisted in browser storage. Configure it for this page session only, or use a trusted server-side gateway in production.
Operation credentials Each key is held in JavaScript memory only and cleared by reload, sign out, or Clear all.
Clear all
${[["create", "Create API key", "New intake and operational records"], ["update", "Update API key", "Existing remote records and retries"], ["search", "Search API key", "Individual receipt RowKey lookups"]].map(([type, label, help]) => `
`).join("")}
Storage inventory Layer Stored information Retention Items ${inventory.map((item) => `${escapeHtml(item.layer)} ${escapeHtml(item.contents)} ${escapeHtml(item.retention)} ${item.count === null ? "Service-managed" : escapeHtml(String(item.count))} `).join("")}
Submission queue Retry or cancel operations that have not received remote acceptance.
${queues.length} ${queues.length ? queues.map((item) => `
${escapeHtml(item.operationType)} ${escapeHtml(item.operationId || item.queueId)} | ${escapeHtml(item.status)} | Attempt ${Number(item.attemptCount || 1)}
${escapeHtml(item.lastError || "Awaiting retry")}
Next retry: ${escapeHtml(item.nextRetryAt ? dateTimeFormatter(item.nextRetryAt) : "Manual")}
Retry Cancel
`).join("") : `
No operations are waiting for retry.
`}
Remote receipts Acknowledgements linked to the operation and record they confirm.
${receipts.length} ${receipts.length ? receipts.slice(0, 25).map((item) => `
${escapeHtml(item.operationType)} Operation ${escapeHtml(item.operationId)} | Record ${escapeHtml(item.recordReference || "Not supplied")}
Receipt ${escapeHtml(item.rowKey || `HTTP ${item.status}`)} | ${dateTimeFormatter(item.submittedAt)}
Open record`).join("") : `
No remote receipts are stored for this profile.
`}
Preserved conflict drafts Attempted edits blocked by optimistic-version checks remain available for review.
${conflictEntries.length} `;
container.querySelector("[data-retry-sync-workspace]")?.addEventListener("click", () => {
container.innerHTML = ` Retrying storage and synchronization evidence...
`;
hydrateSyncWorkspace(container);
});
container.querySelector("[data-remote-credential-form]")?.addEventListener("submit", (event) => {
event.preventDefault();
const type = event.submitter?.value || "create";
const input = container.querySelector(`#remote-${type}-credential`);
const configured = apiService?.configureCredential?.(type, input.value);
input.value = "";
showToast(configured ? `${type[0].toUpperCase()}${type.slice(1)} credential ready` : "Credential required", configured ? "The credential is held in memory for this page session only." : `Enter the ${type} credential first.`, configured ? "success" : "warning");
hydrateSyncWorkspace(container);
});
container.querySelector("[data-clear-remote-credential]")?.addEventListener("click", () => {
apiService?.clearCredential?.();
showToast("Remote credential cleared", "The in-memory credential was removed.", "success");
hydrateSyncWorkspace(container);
});
container.querySelectorAll("[data-retry-queue]").forEach((button) => button.addEventListener("click", async () => {
const queued = queues.find((item) => item.queueId === button.dataset.retryQueue);
if (!queued) return;
button.disabled = true;
const result = await submitRemoteOperation(queued.operationType, queued.payload, `${queued.operationType} retry`, queued);
if (result.ok) await storageService.deleteDurable(activeProfile.profileId, "remote-queue", queued.queueId);
hydrateSyncWorkspace(container);
}));
container.querySelectorAll("[data-cancel-queue]").forEach((button) => button.addEventListener("click", async () => {
await storageService.deleteDurable(activeProfile.profileId, "remote-queue", button.dataset.cancelQueue);
recordActivity("queue-cancel", "Queued operation cancelled", button.dataset.cancelQueue, "Cancelled");
showToast("Queued operation cancelled", "The local retry item was removed; the related local record was preserved.", "success");
hydrateSyncWorkspace(container);
}));
container.querySelectorAll("[data-open-remote-receipt]").forEach((button) => button.addEventListener("click", async () => {
const rowKey = button.dataset.openRemoteReceipt;
if (!rowKey) {
showToast("Receipt unavailable", "This acknowledgement does not include a searchable RowKey.", "warning");
return;
}
if (!validateRemoteProfileConfiguration("search")) return;
const editor = container.querySelector("[data-receipt-record-editor]");
button.disabled = true;
button.innerHTML = ` Loading`;
try {
const result = await apiService.findRecordByReceipt(rowKey);
const remoteRecord = normalizeRemoteReceiptPayload(result.response, rowKey);
renderRemoteReceiptEditor(editor, remoteRecord, {
rowKey,
operationId: button.dataset.receiptOperation,
fetchedAt: result.fetchedAt
});
recordActivity("remote-receipt-lookup", "Remote receipt record opened", `Receipt ${rowKey} was retrieved for local review.`, "Completed", { rowKey, operationId: button.dataset.receiptOperation });
editor.scrollIntoView({ behavior: "smooth", block: "start" });
} catch (error) {
console.warn("Remote receipt lookup failed", error);
showToast("Remote record unavailable", error.message, "danger");
} finally {
button.disabled = false;
button.innerHTML = ` Open record`;
}
}));
}
function normalizeRemoteReceiptPayload(value, rowKey) {
if (typeof value === "string") {
try {
return normalizeRemoteReceiptPayload(JSON.parse(value), rowKey);
} catch (error) {
return { RowKey: rowKey, response: value };
}
}
if (value === null || value === undefined) return { RowKey: rowKey };
if (typeof value !== "object") return { RowKey: rowKey, value };
return JSON.parse(JSON.stringify(value));
}
function collectJsonLeaves(value, path = [], leaves = []) {
if (Array.isArray(value)) {
if (!value.length) leaves.push({ path, value: [], type: "array" });
else value.forEach((item, index) => collectJsonLeaves(item, [...path, index], leaves));
return leaves;
}
if (value && typeof value === "object") {
const entries = Object.entries(value);
if (!entries.length) leaves.push({ path, value: {}, type: "object" });
else entries.forEach(([key, item]) => collectJsonLeaves(item, [...path, key], leaves));
return leaves;
}
leaves.push({ path, value, type: value === null ? "null" : typeof value });
return leaves;
}
function setJsonPath(target, path, value) {
let cursor = target;
path.slice(0, -1).forEach((segment) => { cursor = cursor[segment]; });
cursor[path[path.length - 1]] = value;
}
function coerceJsonFieldValue(control) {
const type = control.dataset.jsonType;
if (type === "number") return control.value === "" ? null : Number(control.value);
if (type === "boolean") return control.value === "true";
if (type === "null") return control.value === "" ? null : control.value;
if (type === "array" || type === "object") {
try { return JSON.parse(control.value || (type === "array" ? "[]" : "{}")); } catch (error) { throw new Error(`${control.dataset.fieldLabel} must contain valid JSON.`); }
}
return control.value;
}
function rebuildRemotePayload(form, originalPayload) {
const payload = JSON.parse(JSON.stringify(originalPayload));
form.querySelectorAll("[data-json-path]").forEach((control) => {
setJsonPath(payload, JSON.parse(control.dataset.jsonPath), coerceJsonFieldValue(control));
});
return payload;
}
function renderRemotePayloadField(entry, index) {
const key = String(entry.path.at(-1) ?? "value");
const label = key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").replace(/^./, (value) => value.toUpperCase());
const breadcrumb = entry.path.slice(0, -1).map(String).join(" > ") || "Root";
const id = `remote-payload-${index}`;
const attributes = `id="${id}" name="${escapeHtml(entry.path.map(String).join("."))}" data-json-path="${escapeHtml(JSON.stringify(entry.path))}" data-json-type="${entry.type}" data-field-label="${escapeHtml(label)}"`;
const readOnly = ["createdat", "updatedat"].includes(key.toLowerCase()) ? " readonly" : "";
let control;
if (entry.type === "boolean") {
control = `True False `;
} else if (entry.type === "number") {
control = ` `;
} else if (entry.type === "array" || entry.type === "object" || String(entry.value ?? "").length > 120) {
const displayValue = entry.type === "array" || entry.type === "object" ? JSON.stringify(entry.value, null, 2) : String(entry.value ?? "");
control = `${escapeHtml(displayValue)} `;
} else {
control = ` `;
}
return `${escapeHtml(label)} ${escapeHtml(breadcrumb)}
${control}${readOnly ? `
Managed by the source service.
` : ""}
`;
}
function renderRemoteReceiptEditor(container, record, context) {
const leaves = collectJsonLeaves(record);
container.classList.remove("d-none");
container.innerHTML = `
Remote receipt record ${escapeHtml(context.rowKey)} ${leaves.length} payload fields expanded from the remote response. Saving reconstructs the original JSON hierarchy.
Operation ${escapeHtml(context.operationId || "Not supplied")} | Fetched ${dateTimeFormatter(context.fetchedAt)}
Close record
${leaves.map(renderRemotePayloadField).join("")}
Choose where to save: local save keeps this remote receipt record in the active browser profile. Remote update also sends the reconstructed JSON payload to the configured endpoint.
Save receipt record locally Save receipt record & update remote
`;
const form = container.querySelector("[data-remote-receipt-form]");
bindRecordValidationReset(form);
const saveRecord = async (submitRemote = false) => {
if (submitRemote && !validateRemoteProfileConfiguration("update")) return;
let localRecord;
try {
localRecord = rebuildRemotePayload(form, record);
} catch (error) {
showToast("Payload validation required", error.message, "danger");
return;
}
const savedAt = new Date().toISOString();
storageService.writeProfile(activeProfile.profileId, `remote-receipt-record:${context.rowKey}`, localRecord);
await storageService.putDurable(activeProfile.profileId, "remote-receipt-records", context.rowKey, localRecord).catch((error) => console.warn("Remote receipt local save failed", error));
recordActivity("remote-receipt-local-save", "Remote receipt record saved locally", `Receipt ${context.rowKey} was saved under the active browser profile.`, "Local", { rowKey: context.rowKey, operationId: context.operationId });
if (!submitRemote) {
showToast("Remote record saved locally", "The reconstructed payload is stored in this browser profile and IndexedDB.", "success");
return;
}
showToast("Updating remote record", "Sending the reconstructed JSON payload with its original structure.", "primary");
try {
const result = await apiService.updateRecord(localRecord);
await storageService.putDurable(activeProfile.profileId, "remote-receipts", `UPDATE-${context.rowKey}-${Date.now()}`, { operationId: context.operationId, operationType: "remote-record-update", rowKey: context.rowKey, status: result.status, response: result.response, submittedAt: result.submittedAt });
recordActivity("remote-record-update", "Remote receipt record updated", `Receipt ${context.rowKey} was accepted by the shared service.`, "Submitted", { rowKey: context.rowKey });
showToast("Remote record updated", "The shared service accepted the reconstructed JSON payload.", "success");
} catch (error) {
showToast("Remote update failed", `${error.message} The reconstructed payload remains saved locally.`, "danger");
}
};
form.addEventListener("submit", (event) => {
event.preventDefault();
saveRecord(false);
});
form.querySelector("[data-save-remote-record='remote']")?.addEventListener("click", () => saveRecord(true));
container.querySelector("[data-close-receipt-editor]")?.addEventListener("click", () => {
container.classList.add("d-none");
container.innerHTML = "";
});
}
function renderCacheGroup(title, description, scope, entries) {
return `
${escapeHtml(title)} ${entries.length}
${escapeHtml(description)}
Clear ${scope === "profile" ? "local changes" : "session cache"}
${entries.length ? entries.map((entry) => {
const datasetKey = scope === "session" ? entry.scopedName.split(":").pop() : "";
const refreshButton = datasetKey && dataUrls[datasetKey]
? `
Refresh`
: "";
return `
${escapeHtml(formatCacheName(entry, scope))}
${escapeHtml(entry.scopedName)} · ${formatBytes(entry.bytes)}
${refreshButton}
Delete
`;
}).join("") : `
No cached items in this section.
`}
`;
}
function formatCacheName(entry, scope) {
const key = scope === "profile" ? entry.scopedName.replace(/^table:/, "") : entry.scopedName.split(":").pop();
const labels = {
requests: "Veteran requests",
requestTable: "Veteran requests",
homeRequests: "Veteran requests",
providers: "Providers",
providerTable: "Providers",
cases: "Case management",
caseTable: "Case management",
reports: "Reports",
reportTable: "Reports",
veterans: "Veteran 360",
veteranTable: "Veteran 360",
coordinatedEntry: "Coordinated Entry",
assessmentTable: "Coordinated Entry",
consents: "Consent Center",
consentTable: "Consent Center",
units: "Bed and Unit Board",
unitTable: "Bed and Unit Board",
partnerOperations: "Agent Operations",
partnerOperationsTable: "Agent Operations"
};
return labels[key] || key.replace(/[-_:]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
function formatBytes(bytes) {
if (bytes < 1024) {
return `${bytes} B`;
}
return `${(bytes / 1024).toFixed(bytes < 10240 ? 1 : 0)} KB`;
}
function bindProfileWorkspace() {
const form = recordModalBody.querySelector("[data-profile-update-form]");
const cacheLists = recordModalBody.querySelector("[data-profile-cache-lists]");
const syncWorkspace = recordModalBody.querySelector("[data-sync-workspace]");
modalPrimaryAction.textContent = "Save profile locally";
storageService.getPersistenceStatus(activeProfile.profileId).then((status) => {
const statusText = cacheLists.querySelector("[data-persistence-status-text]");
const statusCount = cacheLists.querySelector("[data-persistence-status-count]");
if (statusText) {
statusText.textContent = status.indexedDb
? "Profile data is mirrored to IndexedDB for larger drafts, workflow events, document metadata, and activity history."
: "IndexedDB is unavailable; this session is using memory only unless Chrome extension storage is available.";
}
if (statusCount) {
statusCount.textContent = status.indexedDb ? `${status.durableEntries} durable items` : status.mode;
}
}).catch((error) => {
console.warn("Persistence status check failed", error);
});
hydrateSyncWorkspace(syncWorkspace);
modalPrimaryAction.onclick = () => {
if (!form.reportValidity()) {
showToast("Profile incomplete", "Complete the required profile fields before saving.", "danger");
return;
}
showToast("Profile update started", "Saving the updated profile in this browser.", "primary");
const updatedProfile = profileManager.update(activeProfile.profileId, Object.fromEntries(new FormData(form).entries()));
if (!updatedProfile) {
showToast("Profile update failed", "The active profile could not be found.", "danger");
return;
}
activeProfile = updatedProfile;
renderProfileChrome();
applyRoleScope();
if (!canAccessPage(currentPage)) {
modalInstance?.hide();
navigateToPage("home", document.body.dataset.homeUrl, { announce: false });
}
showToast("Profile updated", "Your additional profile information is saved locally.", "success");
};
cacheLists.addEventListener("click", async (event) => {
const deleteButton = event.target.closest("[data-cache-delete]");
const clearButton = event.target.closest("[data-cache-clear]");
const refreshButton = event.target.closest("[data-cache-refresh]");
if (!deleteButton && !clearButton && !refreshButton) {
return;
}
if (refreshButton) {
const datasetKey = refreshButton.dataset.cacheRefresh;
const keys = datasetKey === "all" ? Object.keys(dataUrls) : [datasetKey];
refreshButton.disabled = true;
const originalLabel = refreshButton.innerHTML;
refreshButton.innerHTML = ` Refreshing`;
showToast("Refresh started", datasetKey === "all" ? "Reloading all published datasets." : `Reloading the published ${datasetKey} dataset.`, "primary");
try {
await Promise.all(keys.map((key) => fetchDataset(key, { forceRefresh: true })));
const refreshConflicts = await detectRefreshConflicts(keys);
cacheLists.innerHTML = renderProfileCacheLists();
await renderPage(currentPage, { announce: false });
const label = datasetKey === "all" ? "All hosted data" : formatDatasetLabel(datasetKey);
showToast(`${label} refreshed`, refreshConflicts ? `Local work was preserved; ${refreshConflicts} version conflict${refreshConflicts === 1 ? " was" : "s were"} added to Synchronization for review.` : "The latest published records are now cached. Unsynchronized local work was preserved and no version conflict was detected.", refreshConflicts ? "warning" : "success");
} catch (error) {
console.error("Hosted cache refresh failed", error);
refreshButton.disabled = false;
refreshButton.innerHTML = originalLabel;
showToast("Refresh failed", "The published data could not be refreshed. Your existing local data remains unchanged.", "danger");
}
return;
}
const scope = deleteButton ? deleteButton.dataset.cacheDelete : clearButton.dataset.cacheClear;
if (scope === "application") {
if (clearButton.dataset.confirmed !== "true") {
clearButton.dataset.confirmed = "true";
clearButton.textContent = "Confirm clear and sign out";
showToast("Confirmation required", "Select the button again to permanently remove all BeaReponseCare local data.", "warning");
return;
}
const result = await storageService.clearAllAppEntriesAsync();
if (!result.verified || result.remaining > 0 || result.removed !== result.found) {
showCacheClearResult("Local data", result);
return;
}
const loginUrl = new URL(document.body.dataset.loginUrl, window.location.href);
loginUrl.searchParams.set("localDataCleared", "1");
window.location.replace(loginUrl.href);
return;
}
if (deleteButton) {
let deleted = false;
if (scope === "profile") {
deleted = storageService.removeProfile(activeProfile.profileId, deleteButton.dataset.cacheName);
} else {
deleted = storageService.removeSession(deleteButton.dataset.cacheName);
}
if (!deleted) {
showToast("Cache delete failed", "The browser-local item could not be removed. Reload the page and try again.", "danger");
return;
}
showToast("Cached item deleted", "The selected browser-local item was removed.", "success");
} else if (scope === "profile") {
const result = await storageService.clearProfileEntriesAsync(activeProfile.profileId);
showCacheClearResult("Local changes", result);
} else if (scope === "session") {
const result = storageService.clearSessionEntries();
showCacheClearResult("Session cache", result);
}
cacheLists.innerHTML = renderProfileCacheLists();
if (scope === "profile") {
await renderPage(currentPage, { announce: false });
}
});
}
function formatDatasetLabel(key) {
const labels = {
requests: "Veteran requests",
providers: "Providers",
cases: "Case management",
reports: "Reports"
};
return labels[key] || String(key).replace(/[-_:]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
async function detectRefreshConflicts(datasetKeys) {
const mappings = {
requests: "requestTable", providers: "providerTable", cases: "caseTable", reports: "reportTable",
veterans: "veteranTable", coordinatedEntry: "assessmentTable", consents: "consentTable",
units: "unitTable", partnerOperations: "partnerOperationsTable"
};
let conflicts = 0;
for (const dataKey of datasetKeys) {
const tableId = mappings[dataKey];
if (!tableId) continue;
const state = readLocalTableState(tableId);
const columns = getTableColumns(tableId);
const hostedRows = tableStore[dataKey] || [];
for (let index = 0; index < hostedRows.length; index += 1) {
const hosted = hostedRows[index];
const identity = getRecordIdentity(hosted, columns, index);
const local = state.updates[identity];
if (!local || Number(hosted.version || 1) < Number(local.version || 1)) continue;
const conflictId = `REFRESH-${tableId}-${slugify(identity)}`;
await storageService.putDurable(activeProfile.profileId, "conflict-drafts", conflictId, {
conflictId, tableId, recordIdentity: identity, expectedVersion: Math.max(1, Number(local.version || 1) - 1),
currentVersion: Number(hosted.version || 1), attemptedEdits: local, currentRecord: stripLocalMetadata(hosted),
source: "Hosted refresh", savedAt: new Date().toISOString()
}).catch(() => false);
conflicts += 1;
}
}
return conflicts;
}
function showCacheClearResult(label, result) {
if (result.remaining > 0 || result.removed !== result.found) {
showToast(`${label} clear incomplete`, `${result.remaining} browser-local item${result.remaining === 1 ? "" : "s"} could not be removed.`, "danger");
return;
}
showToast(`${label} cleared`, `${result.removed} browser-local item${result.removed === 1 ? "" : "s"} removed.`, "success");
}
function bindNavigationButtons() {
document.querySelectorAll("[data-nav-page]").forEach((button) => {
if (button.dataset.boundNav === "true") {
return;
}
button.addEventListener("click", () => {
const target = button.dataset.navPage;
const href = resolveNavHref(target);
if (!href) {
showToast("Navigation unavailable", `Could not resolve the ${target} page link from the shared navigation.`, "danger");
return;
}
const drilldown = button.dataset.tableId ? {
tableId: button.dataset.tableId,
key: button.dataset.filterKey,
values: String(button.dataset.filterValues || "").split("|").filter(Boolean),
label: button.dataset.filterLabel || button.textContent.trim()
} : null;
const destination = drilldown ? buildDrilldownUrl(href, drilldown) : href;
if (button.closest("#recordModal") && modalInstance) {
recordModal.addEventListener("hidden.bs.modal", () => {
navigateToPage(target, destination, { drilldown });
}, { once: true });
modalInstance.hide();
return;
}
navigateToPage(target, destination, { drilldown });
});
button.dataset.boundNav = "true";
});
}
function resolveNavHref(pageKey) {
const match = document.querySelector(`.sidebar-nav .nav-link[data-nav-key="${pageKey}"]`);
return match ? match.getAttribute("href") : "";
}
function buildDrilldownUrl(href, drilldown) {
const url = new URL(href, window.location.href);
url.searchParams.set("table", drilldown.tableId);
url.searchParams.set("field", drilldown.key);
url.searchParams.set("values", drilldown.values.join("|"));
url.searchParams.set("view", drilldown.label);
return url.href;
}
function readDrilldownFromUrl() {
const params = new URLSearchParams(window.location.search);
const tableId = params.get("table");
const key = params.get("field");
const values = String(params.get("values") || "").split("|").filter(Boolean);
if (!tableId || !key || values.length === 0) {
return null;
}
return { tableId, key, values, label: params.get("view") || "Linked records" };
}
function applyTableDrilldown(drilldown) {
if (!drilldown || !tableRegistry[drilldown.tableId]) {
return;
}
const registry = tableRegistry[drilldown.tableId];
registry.externalFilter = { key: drilldown.key, values: drilldown.values };
const filter = document.querySelector(`[data-table-filter='${drilldown.tableId}']`);
if (filter) {
filter.value = drilldown.values.length === 1 && Array.from(filter.options).some((option) => option.value === drilldown.values[0])
? drilldown.values[0]
: "";
}
registry.applyFilters();
showToast("Linked view ready", `${drilldown.label}: ${drilldown.values.join(" or ")}.`, "info");
}
function calculateOperationalKpis(requests, cases) {
const periodDays = 14;
const periodStart = Date.now() - (periodDays * 24 * 60 * 60 * 1000);
const inPeriod = (record) => new Date(record.updatedAt || record.createdAt || 0).getTime() >= periodStart;
const placedRequests = requests.filter((record) => ["Assigned", "Checked In", "Completed"].includes(record.status) && inPeriod(record));
const placementHours = placedRequests.map((record) => {
const started = new Date(record.createdAt || 0).getTime();
const completed = new Date(record.assignedAt || record.updatedAt || 0).getTime();
return started && completed >= started ? (completed - started) / 3600000 : null;
}).filter((value) => value !== null);
const firstContactHours = cases.filter(inPeriod).map((record) => {
const started = new Date(record.createdAt || record.openedAt || 0).getTime();
const contacted = new Date(record.firstContactAt || record.updatedAt || 0).getTime();
return started && contacted >= started ? (contacted - started) / 3600000 : null;
}).filter((value) => value !== null);
const average = (values) => values.length ? values.reduce((total, value) => total + value, 0) / values.length : 0;
return {
periodDays,
periodLabel: `Rolling ${periodDays} days`,
placedCount: placedRequests.length,
averagePlacementHours: average(placementHours),
averageFirstContactHours: average(firstContactHours),
unsuccessfulMatches: cases.filter((record) => inPeriod(record) && /declined|no inventory|unsuccessful/i.test(`${record.status} ${record.phase} ${record.nextStep}`)).length,
extensions: cases.filter((record) => inPeriod(record) && String(record.extensionRequested) === "true").length
};
}
function renderWorkflowLinkage(datasets) {
const operation = datasets.operations.find((row) => row.requestId && row.caseId && row.veteranId && row.providerId) || datasets.operations[0] || {};
const request = datasets.requests.find((row) => row.id === operation.requestId) || datasets.requests.find((row) => row.caseId === operation.caseId) || datasets.requests[0] || {};
const caseRecord = datasets.cases.find((row) => row.caseId === operation.caseId) || datasets.cases.find((row) => row.requestId === request.id) || {};
const veteran = datasets.veterans.find((row) => row.veteranId === operation.veteranId) || datasets.veterans.find((row) => row.requestId === request.id) || {};
const assessment = datasets.assessments.find((row) => row.veteranId === veteran.veteranId) || {};
const consent = datasets.consents.find((row) => row.veteranId === veteran.veteranId) || {};
const provider = datasets.providers.find((row) => row.providerId === (operation.providerId || caseRecord.providerId || request.providerId)) || {};
const placementId = operation.placementId || (caseRecord.caseId ? `PLC-${String(caseRecord.caseId).replace(/^CASE-/, "")}` : "");
const node = (page, tableId, key, value, title, id, icon) => !value || !canAccessPage(page) ? "" : `
${escapeHtml(title)} ${escapeHtml(id || value)}
`;
const stages = [
[node("veterans", "veteranTable", "veteranId", veteran.veteranId, veteran.veteranName || request.veteran || "Veteran", veteran.veteranId, "bi-person-vcard")],
[
node("requests", "requestTable", "id", request.id, request.type || "Veteran request", request.id, "bi-journal-check"),
node("coordinatedEntry", "assessmentTable", "assessmentId", assessment.assessmentId, "Assessment", assessment.assessmentId, "bi-ui-checks-grid"),
node("consent", "consentTable", "consentId", consent.consentId, consent.status ? `${consent.status} consent` : "Consent", consent.consentId, "bi-file-earmark-lock2")
],
[node("cases", "caseTable", "caseId", caseRecord.caseId, caseRecord.status ? `${caseRecord.status} case` : "Case", caseRecord.caseId, "bi-kanban")],
[
node("placement", "placementTable", "placementId", placementId, "Placement", placementId, "bi-signpost-split"),
node("providers", "providerTable", "providerId", provider.providerId, "Provider", provider.providerId, "bi-buildings")
],
[node("partnerOperations", "partnerOperationsTable", "coordinationId", operation.coordinationId, operation.workType || "Agent operation", operation.coordinationId, "bi-exclamation-diamond")]
].map((stage) => stage.filter(Boolean)).filter((stage) => stage.length);
return `
Connected form journey One veteran, linked decisions, role-scoped access Select an available node to open the matching record. The visible path reflects the signed-in role.
${escapeHtml(activeProfile.role)}
${stages.map((stage, index) => `${index ? '
' : ""}
${stage.join("")}
`).join("")}
`;
}
async function renderHome() {
const [requests, providers, cases] = await Promise.all([
fetchDataset("requests"),
fetchDataset("providers"),
fetchDataset("cases")
]);
await Promise.all([fetchDataset("veterans"), fetchDataset("coordinatedEntry"), fetchDataset("consents"), fetchDataset("partnerOperations")]);
const effectiveRequests = getEffectiveDatasourceRows("requests");
const effectiveProviders = getEffectiveDatasourceRows("providers");
const effectiveCases = getEffectiveDatasourceRows("cases");
const operationalKpis = calculateOperationalKpis(effectiveRequests, effectiveCases);
const activeStays = effectiveRequests.filter((row) => row.status === "Checked In").length;
const criticalRequests = effectiveRequests.filter((row) => row.priority === "Critical").length;
const approvedProviders = effectiveProviders.filter((row) => row.status === "Available").length;
const openCases = effectiveCases.filter((row) => row.status !== "Closed").length;
pageContent.innerHTML = `
Compassionate agent placement
BeaReponseCare helps veterans move from urgent requests to confirmed stays with speed, visibility, and accountable support.
Review critical requests
Open case timeline
Hosted sample records
${effectiveRequests.length + effectiveProviders.length + effectiveCases.length}
records powering the live portal
Case manager SLA
${operationalKpis.averagePlacementHours.toFixed(1)} hrs
created to assigned/updated, ${operationalKpis.periodLabel.toLowerCase()} (${operationalKpis.placedCount} placements)
Critical request queue
${criticalRequests}
requests requiring priority coordination
${metricLinkCard("bi bi-activity", "Active Stats", String(activeStays), "Open checked-in veteran stays", "requests", "requestTable", "status", ["Checked In"])}
${metricLinkCard("bi bi-exclamation-diamond", "Critical requests", String(criticalRequests), "Open the immediate response queue", "requests", "requestTable", "priority", ["Critical"])}
${metricLinkCard("bi bi-building-check", "Ready providers", String(approvedProviders), "Open providers with available inventory", "providers", "providerTable", "status", ["Available"])}
${metricLinkCard("bi bi-kanban", "Open cases", String(openCases), "Open active and pending case work", "cases", "caseTable", "status", ["Active", "Pending Approval"])}
${renderWorkflowLinkage({ requests: effectiveRequests, providers: effectiveProviders, cases: effectiveCases, veterans: getEffectiveDatasourceRows("veterans"), assessments: getEffectiveDatasourceRows("coordinatedEntry"), consents: getEffectiveDatasourceRows("consents"), operations: getEffectiveDatasourceRows("partnerOperations") })}
Role-based workflows
What each team gets in BeaReponseCare
${storyCard("bi bi-person-heart", "Veterans", "Submit accommodation requests, upload documents, track status, request extensions, and receive check-in instructions.")}
${storyCard("bi bi-building", "Hotels and Housing", "Manage room and unit availability, confirm placements, check veterans in, and submit invoices or voucher confirmations.")}
${storyCard("bi bi-clipboard2-pulse", "Case Managers", "Review eligibility, score urgency, search capacity, approve placements, monitor stays, and close cases with notes.")}
${storyCard("bi bi-graph-up-arrow", "Program Leaders", "Track demand, provider capacity, placement speed, service outcomes, and regional operating trends.")}
P0 coordinated-care controls Move from intake to accountable, consent-aware placement Open the new master-profile, assessment, consent, and live-inventory workflows directly from the command center.
Veteran 360 By-name list, households, eligibility, programs, ownership, and duplicate review.
Coordinated Entry Standardized assessment, scoring, prioritization, overrides, and referral decisions.
Consent Center Purpose-bound sharing, signature evidence, revocation, and disclosure history.
Bed & Unit Board Availability, accessibility, expiring holds, conflicts, reservations, and check-in.
P1 agent operations Close provider responses, SLA tasks, notification delivery, transition plans, and exceptions in one queue.
Open Agent Operations
Live operating snapshot
Active accommodation demand and service pipeline
Data source: published requests feed via Xenhey read URL.
${renderTableBlock("homeRequests", requests.slice(0, 160), [
{ key: "id", label: "Request ID" },
{ key: "customerReferenceNo", label: "Customer Reference No#" },
{ key: "veteran", label: "Veteran" },
{ key: "type", label: "Request Type" },
{ key: "location", label: "Location" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "status", label: "Status", formatter: statusPill }
], "priority")}
Published experience
All sidebar pages now read hosted sample JSON data with search, filtering, CSV export, scrollable tables, and modal record details.
Review provider readiness
`;
bindRecordButtons();
bindTableInteractions("homeRequests", requests.slice(0, 160));
}
async function renderRequests() {
const requests = await fetchDataset("requests");
const effectiveRequests = getEffectiveDatasourceRows("requests");
pageContent.innerHTML = `
Guided intake flow
Veteran request pipeline
Emergency lodging, care coordination, and supplemental specially adapted housing details are captured in one guided request workflow.
Start veteran intake
Auto-route critical
${storyCard("bi bi-file-earmark-medical", "Emergency housing", "Same-day hotel placement for veterans facing displacement, domestic crisis, or immediate safety concerns.")}
${storyCard("bi bi-hospital", "Medical travel lodging", "Short-term stays near VA facilities for appointments, treatment, or recovery visits.")}
${storyCard("bi bi-house-heart", "Transitional housing", "Longer-term placements for stability while veterans wait for permanent housing or benefits approvals.")}
${metricCard("bi bi-send-check", "Submitted", String(effectiveRequests.filter((row) => row.status === "Submitted").length), "New requests waiting for review or document validation")}
${metricCard("bi bi-search-heart", "Under review", String(effectiveRequests.filter((row) => row.status === "Under Review").length), "Case managers actively verifying eligibility and urgency")}
${metricCard("bi bi-pin-map", "Matching", String(effectiveRequests.filter((row) => row.status === "Matching").length), "Provider search and placement scoring in progress")}
${metricCard("bi bi-door-open", "Assigned", String(effectiveRequests.filter((row) => row.status === "Assigned").length), "Veterans notified with room, unit, or shelter details")}
${renderTableBlock("requestTable", requests, [
{ key: "id", label: "Request ID" },
{ key: "customerReferenceNo", label: "Customer Reference No#" },
{ key: "veteran", label: "Veteran" },
{ key: "type", label: "Type" },
{ key: "location", label: "Location" },
{ key: "guests", label: "Guests" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "status", label: "Status", formatter: statusPill }
], "priority")}
`;
bindRecordButtons();
bindTableInteractions("requestTable", requests);
document.querySelector("[data-start-veteran-intake]")?.addEventListener("click", () => openNewRecordEditor("requestTable"));
}
async function renderProviders() {
const providers = await fetchDataset("providers");
const effectiveProviders = getEffectiveDatasourceRows("providers");
const availableUnits = effectiveProviders.reduce((total, row) => total + Number(row.availableUnits || 0), 0);
const accessibleUnits = effectiveProviders.reduce((total, row) => total + Number(row.accessibleRooms || 0), 0);
const freshInventory = effectiveProviders.filter((row) => Date.now() - new Date(row.lastInventoryCheck || row.updatedAt || 0).getTime() <= (24 * 60 * 60 * 1000)).length;
pageContent.innerHTML = `
Provider network coverage
Hotels, shelters, and housing partners
The South Jersey provider workspace tracks full simulated locations, room inventory, accessibility, rates, transportation support, and check-in readiness.
Open provider profile
Update inventory
Notify waitlist partners
${storyCard("bi bi-building", "Hotel partners", "Program-rate hotel inventory supports emergency placements and medical travel stays near VA facilities.")}
${storyCard("bi bi-house-heart", "Housing partners", "Apartment, shelter, and transitional housing partners extend placement options for longer-term stabilization.")}
${storyCard("bi bi-universal-access-circle", "Accessibility and transit", "Accessible rooms, service-animal support, and shuttle coverage stay visible for fast matching decisions.")}
${metricCard("bi bi-door-open", "Available units", String(availableUnits), "Actual availableUnits across the provider network")}
${metricCard("bi bi-universal-access-circle", "Accessible units available", String(accessibleUnits), "Available accessibility-ready rooms or units")}
${metricCard("bi bi-clock-history", "Inventory confirmed in 24h", String(freshInventory), `${effectiveProviders.length} providers tracked with a freshness timestamp`)}
${metricCard("bi bi-truck", "Shuttle-enabled", String(effectiveProviders.filter((row) => row.shuttleSupport === "Yes").length), "Providers with transport support to VA facilities")}
${renderTableBlock("providerTable", providers, [
{ key: "name", label: "Provider" },
{ key: "type", label: "Type" },
{ key: "addressLine1", label: "Street Address" },
{ key: "city", label: "Municipality" },
{ key: "county", label: "County" },
{ key: "availableUnits", label: "Available Units" },
{ key: "accessibleRooms", label: "Accessible Units" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "contact", label: "Primary Contact" },
{ key: "lastInventoryCheck", label: "Inventory Confirmed", formatter: dateTimeFormatter }
], "status")}
Supply recommendation
Prioritize providers with accessibility, shuttle support, and lower utilization when matching critical requests.
`;
bindRecordButtons();
bindTableInteractions("providerTable", providers);
document.querySelector("[data-provider-inventory]")?.addEventListener("click", openProviderInventoryWorkspace);
}
function openProviderInventoryWorkspace() {
const providers = getEffectiveDatasourceRows("providers");
const today = new Date().toISOString().slice(0, 10);
modalState = null;
openRecordModal("Provider inventory update", `
Local-first inventory calendar The update is saved to this profile and IndexedDB. Select remote submission only when the shared demo endpoint should receive the JSON event.
Load sample data
`, "Provider inventory updated");
const form = recordModalBody.querySelector("[data-provider-inventory-form]");
form?.elements.namedItem("providerId")?.addEventListener("change", (event) => {
const provider = providers.find((candidate) => candidate.providerId === event.target.value);
if (!provider) {
return;
}
form.elements.namedItem("availableUnits").value = provider.availableUnits ?? "";
form.elements.namedItem("accessibleRooms").value = provider.accessibleRooms ?? "";
form.elements.namedItem("nightlyRate").value = provider.veteranProgramRate ?? provider.nightlyRate ?? provider.rate ?? "";
});
form?.querySelector("[data-provider-inventory-sample]")?.addEventListener("click", () => {
const provider = providers.find((candidate) => Number(candidate.availableUnits || 0) > 0) || providers[0];
if (!provider) {
showToast("Sample unavailable", "No provider inventory sample is available.", "warning");
return;
}
form.elements.namedItem("providerId").value = provider.providerId;
form.elements.namedItem("providerId")._syncTypeahead?.();
form.elements.namedItem("availableUnits").value = provider.availableUnits ?? 2;
form.elements.namedItem("accessibleRooms").value = provider.accessibleRooms ?? 1;
form.elements.namedItem("nightlyRate").value = provider.veteranProgramRate ?? provider.nightlyRate ?? provider.rate ?? 145;
form.elements.namedItem("inventoryNote").value = "Sample availability confirmed for coordinated veteran placement review.";
showToast("Sample data loaded", "A realistic provider inventory update is ready for review.", "success");
});
const saveInventory = async (submitRemote) => {
if (submitRemote && !validateRemoteProfileConfiguration("update")) {
return;
}
if (!form?.reportValidity()) {
return;
}
const payload = Object.fromEntries(new FormData(form).entries());
const providerIndex = providers.findIndex((provider) => provider.providerId === payload.providerId);
const provider = providers[providerIndex];
if (!provider) {
showToast("Provider required", "Select a provider before saving inventory.", "danger");
return;
}
const eventId = `INV-${Date.now()}`;
const event = { ...payload, eventId, availableUnits: Number(payload.availableUnits), accessibleRooms: Number(payload.accessibleRooms), recordedAt: new Date().toISOString() };
persistRecordPatch("providerTable", provider, providerIndex, {
availableUnits: event.availableUnits,
accessibleRooms: event.accessibleRooms,
veteranProgramRate: payload.nightlyRate,
lastInventoryCheck: event.recordedAt
});
await storageService.putDurable(activeProfile.profileId, "provider-inventory", eventId, event).catch((error) => console.warn("Inventory IndexedDB save failed", error));
recordActivity("provider-inventory", "Provider inventory updated", `${provider.name} reported ${event.availableUnits} available units for ${payload.inventoryDate}.`, "Local", { providerId: provider.providerId, eventId });
refreshConnectedTableState("providerTable");
if (submitRemote) {
const result = await submitRemoteOperation("provider-inventory-update", event, "Provider inventory shared");
if (!result.ok) {
showToast("Inventory saved locally", "The local inventory update was preserved, but remote submission was not accepted.", "warning");
return;
}
}
showToast(submitRemote ? "Inventory saved and submitted" : "Inventory saved locally", submitRemote ? "The provider inventory was stored locally and accepted by the remote API." : "The provider calendar was updated locally only.", "success");
modalInstance?.hide();
};
modalPrimaryAction.textContent = "Save inventory locally";
modalPrimaryAction.onclick = () => saveInventory(false);
modalRemoteAction?.classList.remove("d-none");
if (modalRemoteAction) modalRemoteAction.textContent = "Save inventory & submit";
if (modalRemoteAction) modalRemoteAction.onclick = () => saveInventory(true);
}
async function renderCases() {
const cases = await fetchDataset("cases");
pageContent.innerHTML = `
Case manager operations
Review, approve, assign, and monitor each accommodation case
The case management workflow centralizes notes, extensions, provider confirmations, and closure tasks.
Launch case review
${timelineCard("New request arrives", "Veteran profile, urgency, documents, and consent are checked before the case is scored for action.")}
${timelineCard("Match and approve", "Case managers compare provider inventory, funding rules, family size, accessibility needs, and travel distance.")}
${timelineCard("Stay monitoring", "Check-in, check-out, extension requests, notes, payment handoff, and follow-up support all stay attached to the case.")}
${renderTableBlock("caseTable", cases, [
{ key: "caseId", label: "Case ID" },
{ key: "customerReferenceNo", label: "Customer Reference No#" },
{ key: "veteran", label: "Veteran" },
{ key: "manager", label: "Case Manager" },
{ key: "provider", label: "Provider" },
{ key: "phase", label: "Current Phase" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "nextStep", label: "Next Step" },
{ key: "eta", label: "ETA" }
], "phase")}
`;
bindRecordButtons();
bindTableInteractions("caseTable", cases);
}
function buildPlacementRows(requests, cases, providers) {
return cases.map((caseRecord) => {
const request = requests.find((record) => record.id === caseRecord.requestId) || {};
const provider = providers.find((record) => record.providerId === caseRecord.providerId) || {};
const placed = ["Assigned", "Checked In", "Completed", "Active"].includes(request.status) || caseRecord.status === "Active";
const placementId = `PLC-${String(caseRecord.caseId || "CASE").replace(/^CASE-/, "")}`;
return {
placementId,
__sourceRecordIdentity: `placementId:${placementId}`,
caseId: caseRecord.caseId,
requestId: caseRecord.requestId,
customerReferenceNo: caseRecord.customerReferenceNo || request.customerReferenceNo || "",
veteran: caseRecord.veteran || request.veteran || "",
priority: request.priority || "Medium",
assignedOwner: caseRecord.manager || "Unassigned",
providerId: caseRecord.providerId || request.providerId || "",
provider: caseRecord.provider || provider.name || "Unmatched",
availableUnits: provider.availableUnits ?? "",
holdStatus: "Not held",
approvalStatus: /approval/i.test(caseRecord.phase || "") ? "Pending" : placed ? "Approved" : "Not started",
reservationNumber: placed ? `RSV-${String(caseRecord.caseId || "").replace(/\D/g, "")}` : "",
requestedCheckIn: request.requestedCheckIn || "",
requestedCheckOut: request.requestedCheckOut || "",
fundingSource: caseRecord.fundingSource || "",
status: caseRecord.status || request.status || "Open",
nextStep: caseRecord.nextStep || "Review placement readiness",
createdAt: caseRecord.createdAt || request.createdAt || new Date().toISOString(),
updatedAt: caseRecord.updatedAt || request.updatedAt || new Date().toISOString()
};
});
}
function rankProvidersForRequest(request, providers) {
return providers.map((provider) => {
const available = Number(provider.availableUnits || 0);
const needsAccessibility = /wheelchair|ground-floor|service animal|mobility/i.test(request.accessibilityNeeds || "");
const sameLocation = String(provider.city || "").toLowerCase() === String(request.location || "").toLowerCase();
const accessibleMatch = !needsAccessibility || Number(provider.accessibleRooms || 0) > 0 || provider.accessible === "Yes";
const transportMatch = String(request.transportationNeeded) !== "true" || provider.shuttleSupport === "Yes";
const score = Math.min(40, available * 2)
+ (sameLocation ? 25 : 8)
+ (accessibleMatch ? 20 : 0)
+ (transportMatch ? 10 : 0)
+ (Number(provider.veteranProgramRate || 999) <= 180 ? 5 : 0);
const reasons = [
`${available} units available`,
sameLocation ? "requested city match" : `nearby ${provider.city || "location"}`,
accessibleMatch ? "accessibility compatible" : "accessibility gap",
transportMatch ? "transport compatible" : "transport gap"
];
return { provider, score, reasons };
}).filter((match) => Number(match.provider.availableUnits || 0) > 0)
.sort((left, right) => right.score - left.score)
.slice(0, 5);
}
function renderProviderMatchCards(shortlist) {
return shortlist.length
? shortlist.map((match) => `${match.score} ${escapeHtml(match.provider.name)} ${escapeHtml(match.reasons.join("; "))}
${escapeHtml(match.provider.providerId)} `).join("")
: `No providers currently have available units for matching.
`;
}
function placementReferenceOptions(placements) {
return placements.map((record) => `${escapeHtml(`${record.placementId} - ${record.veteran}`)} `).join("");
}
function placementFormShell(type, title, description, fields, placements) {
return `
${escapeHtml(title)}
${escapeHtml(description)}
Load sample data
Placement record
Select a placement ${placementReferenceOptions(placements)}
${fields}
Not yet saved for this placement
Save this stage locally
Save this stage & submit
`;
}
function renderActivityTimelineMarkup() {
const activities = getActivityHistory().slice(0, 50);
return activities.length ? `
${activities.map((activity) => `
${escapeHtml(activity.title)}
${escapeHtml(activity.status)}
${escapeHtml(activity.details)}
${dateTimeFormatter(activity.occurredAt)} by ${escapeHtml(activity.actor || "Workspace user")}
`).join("")}
` : `No profile activity yet. Save a workflow action to start the timeline.
`;
}
async function renderPlacementOperations() {
await Promise.all([fetchDataset("requests"), fetchDataset("providers"), fetchDataset("cases")]);
const requests = getEffectiveDatasourceRows("requests");
const providers = getEffectiveDatasourceRows("providers");
const cases = getEffectiveDatasourceRows("cases");
const placementRows = buildPlacementRows(requests, cases, providers);
tableStore.placements = cloneRows(placementRows);
const effectivePlacements = resolveTableRows("placementTable", placementRows, getTableColumns("placementTable"));
const focusRequest = requests.find((record) => record.priority === "Critical" && !["Completed", "Checked In"].includes(record.status)) || requests[0] || {};
const shortlist = rankProvidersForRequest(focusRequest, providers);
const triageFields = `
Recommended priority Critical High Medium Low
Authorized override No override Critical High Medium Low
Accountable owner
Escalation deadline
Recommendation reasons and review note Urgency, requested check-in date, safety needs, and available inventory reviewed by a case manager.
`;
const holdFields = `
Provider ${providers.map((record) => `${escapeHtml(`${record.providerId} - ${record.name}`)} `).join("")}
Units held
Hold expires
Match score
Explained match
`;
const approvalFields = `
Funding approval Pending Approved Declined
Authorized nights
Authorized nightly rate
Provider response Pending Accepted Declined
Reservation number
Veteran acknowledgment Pending Received Declined
Check-in instructions
`;
const stayFields = `
Stay or exception event Checked In Checked Out Missed Check-In Early Checkout Urgent Relocation Extension Requested No Inventory Reservation Declined
Event time
Extension decision Not applicable Pending Approved Declined
Transition plan due
Exception, extension, or transition note
`;
const financeFields = `
Voucher ID
Invoice ID
Payment status Pending Invoice Under Review Approved Paid Exception
Approved amount
Invoiced amount
Actual nights
`;
const communicationFields = `
Audience Veteran Case Manager Provider Funder
Accessible channel Email SMS Phone Secure Message
Delivery status Prepared Sent Delivered Failed
Event-based message
`;
pageContent.innerHTML = `
Demonstration boundary
Shared placement transaction prototype
Local records use profile-scoped storage and IndexedDB. "Save and submit" sends an auditable JSON operation to the configured endpoint, but this endpoint is not a production identity provider or authorization system.
Role: ${escapeHtml(activeProfile.role)}
Explainable provider match Shortlist for ${escapeHtml(focusRequest.veteran || "the next priority request")} Scores use availability, requested location, accessibility, transport support, and program rate.
${renderProviderMatchCards(shortlist)}
1. Triage & SLA
2. Match & Hold
3. Approval & Reservation
4. Stay & Exceptions
5. Finance
6. Communications
${placementFormShell("triage", "Rules with human review", "Record the recommendation, reasons, authorized override, owner, and SLA.", triageFields, effectivePlacements)}
${placementFormShell("match-hold", "Match shortlist and availability hold", "Create a time-limited hold to prevent double booking while approval is pending.", holdFields, effectivePlacements)}
${placementFormShell("approval-reservation", "Funding approval and reservation", "Capture authorized nights and rate, provider acceptance, reservation, instructions, and acknowledgment.", approvalFields, effectivePlacements)}
${placementFormShell("stay-exception", "Stay, exception, extension, and transition", "Track check-in, checkout, no inventory, declines, relocations, extensions, and transition planning.", stayFields, effectivePlacements)}
${placementFormShell("finance-reconciliation", "Voucher-to-invoice reconciliation", "Compare approved and invoiced amounts and actual nights before payment.", financeFields, effectivePlacements)}
${placementFormShell("event-notification", "Event-based communications", "Record audience, accessible channel, delivery outcome, and the message history.", communicationFields, effectivePlacements)}
Unified case timeline
Assignments, approvals, confirmations, stay events, and submissions
${renderActivityTimelineMarkup()}
${renderTableBlock("placementTable", placementRows, [
{ key: "placementId", label: "Placement ID" },
{ key: "veteran", label: "Veteran" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "assignedOwner", label: "Owner" },
{ key: "provider", label: "Provider" },
{ key: "holdStatus", label: "Hold" },
{ key: "approvalStatus", label: "Approval" },
{ key: "reservationNumber", label: "Reservation" },
{ key: "status", label: "Status", formatter: statusPill }
], "status")}
`;
bindRecordButtons();
bindTableInteractions("placementTable", placementRows);
bindPlacementWorkflowForms();
bindPlacementSearch(effectivePlacements, requests, providers);
}
function getPlacementWorkflowPatch(workflowType, payload) {
if (workflowType === "triage") {
return { priority: payload.overridePriority || payload.recommendedPriority, assignedOwner: payload.assignedOwner, slaDueAt: payload.slaDueAt, triageReasons: payload.triageReasons };
}
if (workflowType === "match-hold") {
const provider = getEffectiveDatasourceRows("providers").find((record) => record.providerId === payload.providerId);
return { providerId: payload.providerId, provider: provider?.name || "", holdStatus: "Held", holdExpiresAt: payload.holdExpiresAt, matchScore: payload.matchScore, matchReasons: payload.matchReasons };
}
if (workflowType === "approval-reservation") {
return { approvalStatus: payload.approvalStatus, reservationNumber: payload.reservationNumber, providerResponse: payload.providerResponse, authorizedNights: payload.authorizedNights, authorizedRate: payload.authorizedRate, veteranAcknowledgment: payload.veteranAcknowledgment };
}
if (workflowType === "stay-exception") {
return { status: payload.stayEvent, lastStayEventAt: payload.eventAt, extensionDecision: payload.extensionDecision, nextStep: payload.eventNote, transitionPlanDue: payload.transitionPlanDue };
}
if (workflowType === "finance-reconciliation") {
const variance = Number(payload.invoicedAmount || 0) - Number(payload.approvedAmount || 0);
return { paymentStatus: payload.paymentStatus, voucherId: payload.voucherId, invoiceId: payload.invoiceId, invoiceVariance: variance, actualNights: payload.actualNights };
}
return { lastNotificationAudience: payload.audience, lastNotificationChannel: payload.channel, lastNotificationStatus: payload.deliveryStatus, lastNotificationAt: new Date().toISOString() };
}
function setPlacementFormValue(form, name, value) {
if (!form || value === null || value === undefined || value === "") {
return;
}
const field = form.elements.namedItem(name);
if (!field) {
return;
}
if (field.options && !Array.from(field.options).some((option) => option.value === String(value))) {
return;
}
field.value = String(value);
field.dispatchEvent(new Event("input", { bubbles: true }));
field.dispatchEvent(new Event("change", { bubbles: true }));
}
function getPlacementStageDrafts() {
const drafts = storageService.readProfile(activeProfile.profileId, "placement-stage-drafts", {});
return drafts && typeof drafts === "object" && !Array.isArray(drafts) ? drafts : {};
}
function getPlacementStageDraft(placementId) {
return getPlacementStageDrafts()[placementId] || null;
}
function updatePlacementStageStatus(form, stageDraft) {
const status = form?.querySelector("[data-placement-stage-status]");
if (!status) {
return;
}
if (!stageDraft?.savedAt) {
status.innerHTML = ' Not yet saved for this placement';
return;
}
status.innerHTML = ` Saved locally ${escapeHtml(dateTimeFormatter(stageDraft.savedAt))}`;
}
function restorePlacementStageDrafts(placementId) {
const placementDraft = getPlacementStageDraft(placementId);
const forms = Array.from(document.querySelectorAll("[data-placement-workflow-form]"));
forms.forEach((form) => {
const stageId = form.dataset.placementWorkflowForm;
const stageDraft = placementDraft?.stages?.[stageId] || null;
Object.entries(stageDraft?.fields || {}).forEach(([name, value]) => {
if (name !== "placementId") {
setPlacementFormValue(form, name, value);
}
});
updatePlacementStageStatus(form, stageDraft);
});
return placementDraft;
}
async function savePlacementStageDraft(placementId, stageId, fields) {
const drafts = getPlacementStageDrafts();
const savedAt = new Date().toISOString();
const previous = drafts[placementId] || { placementId, stages: {}, createdAt: savedAt };
const stageFields = { ...fields };
delete stageFields.placementId;
const stageDraft = {
stageId,
fields: stageFields,
savedAt,
savedBy: activeProfile.displayName
};
const placementDraft = {
...previous,
placementId,
stages: { ...(previous.stages || {}), [stageId]: stageDraft },
updatedAt: savedAt
};
drafts[placementId] = placementDraft;
storageService.writeProfile(activeProfile.profileId, "placement-stage-drafts", drafts);
await storageService.putDurable(activeProfile.profileId, "placement-stage-drafts", placementId, placementDraft);
return placementDraft;
}
function applyPlacementSearchSelection(placement, requests, providers) {
const request = requests.find((record) => record.id === placement.requestId)
|| requests.find((record) => record.caseId === placement.caseId)
|| {};
const rankedProviders = rankProvidersForRequest(request, providers);
const matchedProvider = providers.find((record) => record.providerId === placement.providerId) || rankedProviders[0]?.provider || null;
const topMatch = rankedProviders.find((match) => match.provider.providerId === matchedProvider?.providerId) || rankedProviders[0] || null;
const forms = Array.from(document.querySelectorAll("[data-placement-workflow-form]"));
forms.forEach((form) => {
const placementSelect = form.elements.namedItem("placementId");
if (!placementSelect) {
return;
}
if (!Array.from(placementSelect.options).some((option) => option.value === placement.placementId)) {
placementSelect.add(new Option(`${placement.placementId} - ${placement.veteran || request.veteran || "Veteran"}`, placement.placementId), 0);
}
placementSelect.value = placement.placementId;
});
const firstPlacementSelect = forms[0]?.elements.namedItem("placementId");
if (firstPlacementSelect) {
firstPlacementSelect.dispatchEvent(new Event("change", { bubbles: true }));
}
const triageForm = document.querySelector("[data-placement-workflow-form='triage']");
setPlacementFormValue(triageForm, "recommendedPriority", request.priority || placement.priority);
setPlacementFormValue(triageForm, "assignedOwner", placement.assignedOwner === "Unassigned" ? activeProfile.displayName : placement.assignedOwner);
setPlacementFormValue(triageForm, "triageReasons", `${request.priority || placement.priority || "Current"} priority request ${request.id || placement.requestId || ""}; check-in ${request.requestedCheckIn || placement.requestedCheckIn || "not set"}; accessibility ${request.accessibilityNeeds || "not reported"}; transportation ${String(request.transportationNeeded) === "true" ? "required" : "not required"}.`);
const holdForm = document.querySelector("[data-placement-workflow-form='match-hold']");
setPlacementFormValue(holdForm, "providerId", matchedProvider?.providerId || placement.providerId);
setPlacementFormValue(holdForm, "unitsHeld", Math.max(1, Number(request.guests || 1)));
setPlacementFormValue(holdForm, "matchScore", topMatch?.score || 0);
setPlacementFormValue(holdForm, "matchReasons", topMatch?.reasons.join("; ") || "Selected from the connected placement record.");
const checkIn = new Date(`${request.requestedCheckIn || placement.requestedCheckIn || ""}T12:00:00`);
const checkOut = new Date(`${request.requestedCheckOut || placement.requestedCheckOut || ""}T12:00:00`);
const requestedNights = Number.isFinite(checkIn.getTime()) && Number.isFinite(checkOut.getTime())
? Math.max(1, Math.round((checkOut.getTime() - checkIn.getTime()) / (24 * 60 * 60 * 1000)))
: 1;
const nightlyRate = Number(matchedProvider?.veteranProgramRate || 0);
const approvalForm = document.querySelector("[data-placement-workflow-form='approval-reservation']");
setPlacementFormValue(approvalForm, "approvalStatus", ["Approved", "Pending", "Declined"].includes(placement.approvalStatus) ? placement.approvalStatus : "Pending");
setPlacementFormValue(approvalForm, "authorizedNights", requestedNights);
setPlacementFormValue(approvalForm, "authorizedRate", nightlyRate);
setPlacementFormValue(approvalForm, "reservationNumber", placement.reservationNumber);
const stayForm = document.querySelector("[data-placement-workflow-form='stay-exception']");
setPlacementFormValue(stayForm, "transitionPlanDue", request.requestedCheckOut || placement.requestedCheckOut);
setPlacementFormValue(stayForm, "eventNote", `Selected ${placement.placementId} for ${placement.veteran}; requested stay ${request.requestedCheckIn || placement.requestedCheckIn || "not set"} through ${request.requestedCheckOut || placement.requestedCheckOut || "not set"}.`);
const financeForm = document.querySelector("[data-placement-workflow-form='finance-reconciliation']");
setPlacementFormValue(financeForm, "approvedAmount", nightlyRate ? (nightlyRate * requestedNights).toFixed(2) : "");
setPlacementFormValue(financeForm, "actualNights", requestedNights);
const communicationForm = document.querySelector("[data-placement-workflow-form='event-notification']");
setPlacementFormValue(communicationForm, "message", `Placement ${placement.placementId} for ${placement.veteran} is ready for workflow review.`);
const matchTitle = document.querySelector("[data-placement-match-title]");
const matchList = document.querySelector("[data-placement-match-list]");
if (matchTitle) {
matchTitle.textContent = placement.veteran || request.veteran || placement.placementId;
}
if (matchList) {
matchList.innerHTML = renderProviderMatchCards(rankedProviders);
}
restorePlacementStageDrafts(placement.placementId);
showToast("Placement selected", `${placement.placementId} populated all six workflow tabs and refreshed the provider shortlist.`, "success");
}
function createPageRefreshControl(pageKey, label, datasetKeys, options = {}) {
const searchShell = searchInput?.closest(".search-shell");
if (!searchShell?.parentElement) {
return null;
}
const displayLabel = `${label.charAt(0).toUpperCase()}${label.slice(1)}`;
const toolbar = document.createElement("div");
const refreshButton = document.createElement("button");
toolbar.className = "placement-search-toolbar";
refreshButton.type = "button";
refreshButton.className = "placement-refresh-button";
refreshButton.dataset.pageRefresh = pageKey;
if (options.placement) {
refreshButton.dataset.placementRefresh = "true";
}
refreshButton.setAttribute("aria-label", `Refresh ${label} data`);
refreshButton.title = `Refresh ${label} data`;
refreshButton.innerHTML = ' ';
searchShell.before(toolbar);
toolbar.append(searchShell, refreshButton);
const handleRefresh = async () => {
refreshButton.disabled = true;
refreshButton.setAttribute("aria-busy", "true");
refreshButton.innerHTML = ' ';
options.beforeRefresh?.();
showToast(`${displayLabel} refresh started`, `Reloading ${datasetKeys.length === 1 ? "the published dataset" : "the related published datasets"} while preserving local records.`, "primary");
try {
await Promise.all(datasetKeys.map((key) => fetchDataset(key, { forceRefresh: true })));
await renderPage(pageKey, { announce: false });
showToast(`${displayLabel} data refreshed`, "The latest hosted records are loaded and profile-local changes remain available.", "success");
} catch (error) {
console.error(`${displayLabel} refresh failed`, error);
refreshButton.disabled = false;
refreshButton.removeAttribute("aria-busy");
refreshButton.innerHTML = ' ';
showToast("Refresh failed", `${displayLabel} data could not be refreshed. Existing records remain available.`, "danger");
}
};
refreshButton.addEventListener("click", handleRefresh);
return {
refreshButton,
searchShell,
toolbar,
cleanup() {
refreshButton.removeEventListener("click", handleRefresh);
if (toolbar.isConnected) {
toolbar.replaceWith(searchShell);
}
}
};
}
function bindPageRefresh(pageKey, config) {
const control = createPageRefreshControl(pageKey, config.label, config.datasets);
if (control) {
searchInput._pageRefreshCleanup = () => {
control.cleanup();
delete searchInput._pageRefreshCleanup;
};
}
}
function bindPageHeaderSearch(pageKey, tableId) {
const registry = tableRegistry[tableId];
if (!searchInput || !registry) {
return;
}
const searchShell = searchInput.closest(".search-shell");
const columns = getTableColumns(tableId);
const menu = document.createElement("div");
let activeIndex = -1;
let visibleSuggestions = [];
menu.className = "placement-search-menu";
menu.dataset.pageSearchMenu = pageKey;
menu.id = `${pageKey}-header-search-results`;
menu.setAttribute("role", "listbox");
document.body.append(menu);
searchInput.autocomplete = "off";
searchInput.setAttribute("role", "combobox");
searchInput.setAttribute("aria-autocomplete", "list");
searchInput.setAttribute("aria-controls", menu.id);
searchInput.setAttribute("aria-expanded", "false");
const positionMenu = () => {
if (!menu.classList.contains("show")) {
return;
}
const rect = (searchShell || searchInput).getBoundingClientRect();
const padding = 12;
const width = Math.min(Math.max(rect.width, 300), window.innerWidth - (padding * 2));
menu.style.left = `${Math.max(padding, Math.min(rect.left, window.innerWidth - width - padding))}px`;
menu.style.top = `${Math.min(rect.bottom + 8, window.innerHeight - 120)}px`;
menu.style.width = `${width}px`;
};
const closeMenu = () => {
menu.classList.remove("show");
searchInput.setAttribute("aria-expanded", "false");
searchInput.removeAttribute("aria-activedescendant");
activeIndex = -1;
};
const chooseSuggestion = async (entry) => {
searchInput.value = entry.suggestion.label;
closeMenu();
await openRecordEditor(tableId, entry.index, entry.record);
};
const setActiveOption = (nextIndex) => {
const options = Array.from(menu.querySelectorAll("[data-page-search-option]"));
if (!options.length) {
activeIndex = -1;
return;
}
activeIndex = (nextIndex + options.length) % options.length;
options.forEach((option, index) => option.classList.toggle("active", index === activeIndex));
options[activeIndex].scrollIntoView({ block: "nearest" });
searchInput.setAttribute("aria-activedescendant", options[activeIndex].id);
};
const renderSuggestions = () => {
const term = searchInput.value.trim().toLowerCase();
const seen = new Set();
visibleSuggestions = (tableRegistry[tableId]?.rows || registry.rows).map((record, index) => ({
record,
index,
suggestion: getTableSearchSuggestion(record, columns, tableId)
})).filter((entry) => {
const value = entry.suggestion.value;
return (!term || entry.suggestion.searchText.includes(term)) && !seen.has(value) && seen.add(value);
}).slice(0, 12);
menu.replaceChildren();
visibleSuggestions.forEach((entry, index) => {
const option = document.createElement("button");
option.type = "button";
option.className = "placement-search-option";
option.id = `${pageKey}-header-search-option-${index}`;
option.dataset.pageSearchOption = pageKey;
option.dataset.value = entry.suggestion.value;
option.setAttribute("role", "option");
option.innerHTML = `${escapeHtml(entry.suggestion.label)} ${entry.suggestion.meta ? `${escapeHtml(entry.suggestion.meta)} ` : ""}`;
option.addEventListener("mousedown", (event) => event.preventDefault());
option.addEventListener("click", () => chooseSuggestion(entry));
menu.append(option);
});
if (!visibleSuggestions.length) {
const empty = document.createElement("div");
empty.className = "placement-search-empty";
empty.textContent = "No matching records on this page";
menu.append(empty);
}
activeIndex = -1;
menu.classList.add("show");
searchInput.setAttribute("aria-expanded", "true");
positionMenu();
};
const handleKeydown = (event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!menu.classList.contains("show")) {
renderSuggestions();
}
setActiveOption(activeIndex + (event.key === "ArrowDown" ? 1 : -1));
} else if (event.key === "Enter" && activeIndex >= 0 && visibleSuggestions[activeIndex]) {
event.preventDefault();
chooseSuggestion(visibleSuggestions[activeIndex]);
} else if (event.key === "Escape") {
closeMenu();
}
};
const handleBlur = () => window.setTimeout(closeMenu, 120);
const handleViewportChange = () => positionMenu();
searchInput.addEventListener("focus", renderSuggestions);
searchInput.addEventListener("input", renderSuggestions);
searchInput.addEventListener("keydown", handleKeydown);
searchInput.addEventListener("blur", handleBlur);
window.addEventListener("resize", handleViewportChange);
window.addEventListener("scroll", handleViewportChange, true);
searchInput._pageSearchCleanup = () => {
searchInput.removeEventListener("focus", renderSuggestions);
searchInput.removeEventListener("input", renderSuggestions);
searchInput.removeEventListener("keydown", handleKeydown);
searchInput.removeEventListener("blur", handleBlur);
window.removeEventListener("resize", handleViewportChange);
window.removeEventListener("scroll", handleViewportChange, true);
searchInput.removeAttribute("role");
searchInput.removeAttribute("aria-autocomplete");
searchInput.removeAttribute("aria-controls");
searchInput.removeAttribute("aria-expanded");
searchInput.removeAttribute("aria-activedescendant");
menu.remove();
delete searchInput._pageSearchCleanup;
};
}
function bindPlacementSearch(placements, requests, providers) {
if (!searchInput) {
return;
}
let closeMenu = () => {};
const refreshControl = createPageRefreshControl("placement", "placement", ["requests", "providers", "cases"], {
placement: true,
beforeRefresh: () => closeMenu()
});
const searchShell = refreshControl?.searchShell || searchInput.closest(".search-shell");
const menu = document.createElement("div");
const getCurrentRequests = () => getEffectiveDatasourceRows("requests") || requests;
const getCurrentProviders = () => getEffectiveDatasourceRows("providers") || providers;
const buildOptions = () => {
const currentPlacements = tableRegistry.placementTable?.rows || placements;
const currentRequests = getCurrentRequests();
return currentPlacements.map((placement) => {
const request = currentRequests.find((record) => record.id === placement.requestId) || {};
return {
placement,
label: `${placement.placementId} - ${placement.veteran || request.veteran || "Veteran"}`,
meta: [placement.requestId, placement.caseId, placement.customerReferenceNo, request.location, placement.provider].filter(Boolean).join(" | "),
searchText: [placement.placementId, placement.veteran, placement.requestId, placement.caseId, placement.customerReferenceNo, request.location, placement.provider].filter(Boolean).join(" ").toLowerCase()
};
});
};
let activeIndex = -1;
let visibleOptions = [];
menu.className = "placement-search-menu";
menu.dataset.placementSearchMenu = "true";
menu.id = "placement-search-results";
menu.setAttribute("role", "listbox");
document.body.append(menu);
searchInput.placeholder = "Search placement, veteran, request, case, or reference";
searchInput.autocomplete = "off";
searchInput.setAttribute("role", "combobox");
searchInput.setAttribute("aria-autocomplete", "list");
searchInput.setAttribute("aria-controls", menu.id);
searchInput.setAttribute("aria-expanded", "false");
const positionMenu = () => {
if (!menu.classList.contains("show")) {
return;
}
const rect = (searchShell || searchInput).getBoundingClientRect();
const padding = 12;
const width = Math.min(Math.max(rect.width, 300), window.innerWidth - (padding * 2));
const left = Math.max(padding, Math.min(rect.left, window.innerWidth - width - padding));
menu.style.left = `${left}px`;
menu.style.top = `${Math.min(rect.bottom + 8, window.innerHeight - 120)}px`;
menu.style.width = `${width}px`;
};
closeMenu = () => {
menu.classList.remove("show");
searchInput.setAttribute("aria-expanded", "false");
searchInput.removeAttribute("aria-activedescendant");
activeIndex = -1;
};
const selectOption = (option) => {
searchInput.value = option.label;
applyPlacementSearchSelection(option.placement, getCurrentRequests(), getCurrentProviders());
closeMenu();
searchInput.focus();
};
const setActiveOption = (nextIndex) => {
const buttons = Array.from(menu.querySelectorAll("[data-placement-search-option]"));
if (!buttons.length) {
activeIndex = -1;
return;
}
activeIndex = (nextIndex + buttons.length) % buttons.length;
buttons.forEach((button, index) => button.classList.toggle("active", index === activeIndex));
buttons[activeIndex].scrollIntoView({ block: "nearest" });
searchInput.setAttribute("aria-activedescendant", buttons[activeIndex].id);
};
const renderOptions = () => {
const term = searchInput.value.trim().toLowerCase();
visibleOptions = buildOptions().filter((option) => !term || option.searchText.includes(term)).slice(0, 20);
menu.replaceChildren();
visibleOptions.forEach((option, index) => {
const button = document.createElement("button");
button.type = "button";
button.className = "placement-search-option";
button.id = `placement-search-option-${index}`;
button.dataset.placementSearchOption = option.placement.placementId;
button.setAttribute("role", "option");
button.innerHTML = `${escapeHtml(option.label)} ${escapeHtml(option.meta)} `;
button.addEventListener("mousedown", (event) => event.preventDefault());
button.addEventListener("click", () => selectOption(option));
menu.append(button);
});
if (!visibleOptions.length) {
const empty = document.createElement("div");
empty.className = "placement-search-empty";
empty.textContent = "No matching placement records";
menu.append(empty);
}
activeIndex = -1;
menu.classList.add("show");
searchInput.setAttribute("aria-expanded", "true");
positionMenu();
};
const handleFocus = () => renderOptions();
const handleInput = () => renderOptions();
const handleKeydown = (event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!menu.classList.contains("show")) {
renderOptions();
}
setActiveOption(activeIndex + (event.key === "ArrowDown" ? 1 : -1));
} else if (event.key === "Enter" && activeIndex >= 0 && visibleOptions[activeIndex]) {
event.preventDefault();
selectOption(visibleOptions[activeIndex]);
} else if (event.key === "Escape") {
closeMenu();
}
};
const handleBlur = () => window.setTimeout(closeMenu, 120);
const handleViewportChange = () => positionMenu();
searchInput.addEventListener("focus", handleFocus);
searchInput.addEventListener("input", handleInput);
searchInput.addEventListener("keydown", handleKeydown);
searchInput.addEventListener("blur", handleBlur);
window.addEventListener("resize", handleViewportChange);
window.addEventListener("scroll", handleViewportChange, true);
searchInput._refreshPlacementSearch = () => {
if (menu.classList.contains("show") || document.activeElement === searchInput) {
renderOptions();
}
};
searchInput._placementSearchCleanup = () => {
searchInput.removeEventListener("focus", handleFocus);
searchInput.removeEventListener("input", handleInput);
searchInput.removeEventListener("keydown", handleKeydown);
searchInput.removeEventListener("blur", handleBlur);
window.removeEventListener("resize", handleViewportChange);
window.removeEventListener("scroll", handleViewportChange, true);
searchInput.removeAttribute("role");
searchInput.removeAttribute("aria-autocomplete");
searchInput.removeAttribute("aria-controls");
searchInput.removeAttribute("aria-expanded");
searchInput.removeAttribute("aria-activedescendant");
menu.remove();
refreshControl?.cleanup();
delete searchInput._refreshPlacementSearch;
delete searchInput._placementSearchCleanup;
};
}
function serializePlacementWorkflow(activeForm) {
const forms = Array.from(document.querySelectorAll("[data-placement-workflow-form]"));
const activeStepId = activeForm.dataset.placementWorkflowForm;
const sharedPlacementId = String(new FormData(activeForm).get("placementId") || "");
const placementDraft = getPlacementStageDraft(sharedPlacementId);
const steps = forms.map((form, index) => {
const stageId = form.dataset.placementWorkflowForm;
const savedStage = placementDraft?.stages?.[stageId] || null;
const fields = {
...(savedStage?.fields || {}),
...Object.fromEntries(new FormData(form).entries())
};
if (sharedPlacementId) {
fields.placementId = sharedPlacementId;
}
const requiredControls = Array.from(form.querySelectorAll("[required]"));
const isComplete = requiredControls.every((control) => String(control.value || "").trim() !== "");
return {
stepNumber: index + 1,
stepId: stageId,
stepTitle: form.querySelector(".section-kicker")?.textContent.trim() || `Step ${index + 1}`,
isActiveStep: form === activeForm,
isComplete,
savedLocally: Boolean(savedStage),
savedAt: savedStage?.savedAt || null,
fields
};
});
const activeStep = steps.find((step) => step.stepId === activeStepId);
const capturedAt = new Date().toISOString();
return {
schemaVersion: "1.0",
workflowId: `WF-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
workflowType: activeStepId,
placementId: sharedPlacementId,
primaryKey: {
field: "placementId",
value: sharedPlacementId
},
activeStep: {
stepNumber: activeStep?.stepNumber || 1,
stepId: activeStepId,
stepTitle: activeStep?.stepTitle || activeStepId
},
steps,
stepCount: steps.length,
completedStepCount: steps.filter((step) => step.isComplete).length,
profileId: activeProfile.profileId,
actor: activeProfile.displayName,
organization: activeProfile.organization,
capturedAt,
createdAt: capturedAt
};
}
function findResponseRowKey(value, depth = 0) {
if (value === null || value === undefined || depth > 8) {
return "";
}
if (typeof value === "string") {
try {
return findResponseRowKey(JSON.parse(value), depth + 1);
} catch (error) {
return "";
}
}
if (typeof value !== "object") {
return "";
}
const entries = Object.entries(value);
const rowKeyEntry = entries.find(([key]) => key.toLowerCase() === "rowkey");
if (rowKeyEntry && rowKeyEntry[1] !== null && rowKeyEntry[1] !== undefined) {
return String(rowKeyEntry[1]).trim();
}
for (const [, nestedValue] of entries) {
const nestedRowKey = findResponseRowKey(nestedValue, depth + 1);
if (nestedRowKey) {
return nestedRowKey;
}
}
return "";
}
function formatPlacementIdFromRowKey(rowKey) {
const normalized = String(rowKey || "").trim().replace(/^PLC[_-]/i, "");
return normalized ? `PLC_${normalized}` : "";
}
function updatePlacementReferenceOptions(previousPlacementId, nextPlacementId) {
if (!previousPlacementId || !nextPlacementId || previousPlacementId === nextPlacementId) {
return;
}
document.querySelectorAll("[data-placement-workflow-form] select[name='placementId']").forEach((select) => {
const option = Array.from(select.options).find((candidate) => candidate.value === previousPlacementId);
if (option) {
option.value = nextPlacementId;
option.textContent = option.textContent.replace(previousPlacementId, nextPlacementId);
}
select.value = nextPlacementId;
});
}
async function migratePlacementStageDraft(previousPlacementId, nextPlacementId) {
if (!previousPlacementId || !nextPlacementId || previousPlacementId === nextPlacementId) {
return;
}
const drafts = getPlacementStageDrafts();
const previousDraft = drafts[previousPlacementId];
if (!previousDraft) {
return;
}
const migratedDraft = {
...previousDraft,
placementId: nextPlacementId,
previousPlacementId,
updatedAt: new Date().toISOString()
};
delete drafts[previousPlacementId];
drafts[nextPlacementId] = migratedDraft;
storageService.writeProfile(activeProfile.profileId, "placement-stage-drafts", drafts);
await storageService.putDurable(activeProfile.profileId, "placement-stage-drafts", nextPlacementId, migratedDraft);
await storageService.deleteDurable(activeProfile.profileId, "placement-stage-drafts", previousPlacementId).catch(() => false);
}
async function capturePlacementResponse(result, submissionEnvelope) {
const rowKey = findResponseRowKey(result.response);
const responsePlacementId = formatPlacementIdFromRowKey(rowKey);
const placementId = responsePlacementId || submissionEnvelope.placementId;
const responseCapture = {
ok: Boolean(result.ok),
status: result.status || 0,
receivedAt: result.submittedAt || new Date().toISOString(),
rowKey: rowKey || null,
placementId,
activeStep: submissionEnvelope.activeStep,
response: result.response ?? null,
error: result.error || null
};
const captures = storageService.readProfile(activeProfile.profileId, "placement-response-captures", []);
captures.unshift(responseCapture);
storageService.writeProfile(activeProfile.profileId, "placement-response-captures", captures.slice(0, 500));
await storageService.putDurable(activeProfile.profileId, "placement-response", submissionEnvelope.workflowId, responseCapture).catch((error) => {
console.warn("Placement response IndexedDB write failed", error);
});
if (responsePlacementId && submissionEnvelope.placementId) {
const rows = resolveTableRows("placementTable", tableStore.placements || [], getTableColumns("placementTable"));
const rowIndex = rows.findIndex((record) => record.placementId === submissionEnvelope.placementId);
if (rowIndex >= 0) {
persistRecordPatch("placementTable", rows[rowIndex], rowIndex, {
placementId: responsePlacementId,
endpointRowKey: rowKey,
endpointResponseAt: responseCapture.receivedAt
});
refreshConnectedTableState("placementTable");
}
updatePlacementReferenceOptions(submissionEnvelope.placementId, responsePlacementId);
await migratePlacementStageDraft(submissionEnvelope.placementId, responsePlacementId);
recordActivity("placement-response", "Placement ID assigned from endpoint response", `${rowKey} was stored as ${responsePlacementId}.`, "Completed", {
placementId: responsePlacementId,
rowKey
});
}
return responseCapture;
}
function bindPlacementWorkflowForms() {
const defaultDeadline = new Date(Date.now() + (4 * 60 * 60 * 1000)).toISOString().slice(0, 16);
const forms = Array.from(document.querySelectorAll("[data-placement-workflow-form]"));
const placementRows = getEffectiveDatasourceRows("placements");
forms.forEach((form) => {
form.querySelectorAll("input[type='datetime-local']").forEach((input) => {
if (!input.value) {
input.value = defaultDeadline;
}
});
form.querySelector("select[name='placementId']")?.addEventListener("change", (event) => {
forms.forEach((candidate) => {
const placementSelect = candidate.querySelector("select[name='placementId']");
if (placementSelect && Array.from(placementSelect.options).some((option) => option.value === event.target.value)) {
placementSelect.value = event.target.value;
}
});
restorePlacementStageDrafts(event.target.value);
});
form.querySelector("[data-placement-sample]")?.addEventListener("click", () => {
const placement = placementRows.find((record) => record.status !== "Completed") || placementRows[0];
if (!placement) {
showToast("Sample unavailable", "No placement sample is available for this stage.", "warning");
return;
}
const sampleValues = {
...placement,
placementId: placement.placementId,
caseManager: placement.caseManager || placement.assignedOwner || "Jordan Ellis",
assignedOwner: placement.assignedOwner || placement.caseManager || "Jordan Ellis",
status: placement.status || "In progress",
approvalStatus: placement.approvalStatus || "Pending",
actionOutcome: placement.actionOutcome || "In progress",
communicationChannel: placement.communicationChannel || "Secure message",
actionDeadline: defaultDeadline,
notes: placement.notes || "Sample stage data loaded for review before saving."
};
Array.from(form.elements).forEach((control) => {
if (!control.name || control.disabled || control.readOnly) return;
const value = sampleValues[control.name];
if (value === undefined || value === null) return;
if (control.tagName === "SELECT" && !Array.from(control.options).some((option) => option.value === String(value))) return;
control.value = String(value);
control._syncTypeahead?.();
control.dispatchEvent(new Event("change", { bubbles: true }));
});
showToast("Sample data loaded", "This placement stage is populated with realistic linked values. Review before saving this stage.", "success");
});
form.querySelectorAll("[data-placement-submit]").forEach((button) => {
button.addEventListener("click", async () => {
if (button.dataset.placementSubmit === "remote" && !validateRemoteProfileConfiguration("update")) {
return;
}
if (!form.reportValidity()) {
showToast("Workflow incomplete", "Complete the required fields before saving this operation.", "danger");
return;
}
if (!canPerform("placement")) {
showToast("Permission required", `${activeProfile.role} cannot update agent placement.`, "danger");
return;
}
const workflowType = form.dataset.placementWorkflowForm;
const activeFields = Object.fromEntries(new FormData(form).entries());
try {
const placementDraft = await savePlacementStageDraft(activeFields.placementId, workflowType, activeFields);
updatePlacementStageStatus(form, placementDraft.stages[workflowType]);
} catch (error) {
console.error("Placement stage local save failed", error);
showToast("Stage not saved", "This stage could not be written to IndexedDB. Check browser storage permissions and try again.", "danger");
return;
}
const submissionEnvelope = serializePlacementWorkflow(form);
const activeStepData = submissionEnvelope.steps.find((step) => step.stepId === workflowType)?.fields || {};
const workflows = storageService.readProfile(activeProfile.profileId, "placement-workflows", []);
workflows.unshift(submissionEnvelope);
storageService.writeProfile(activeProfile.profileId, "placement-workflows", workflows.slice(0, 1000));
await storageService.putDurable(activeProfile.profileId, "placement-workflow", submissionEnvelope.workflowId, submissionEnvelope).catch((error) => {
console.warn("Placement workflow IndexedDB write failed", error);
});
const rows = resolveTableRows("placementTable", tableStore.placements || [], getTableColumns("placementTable"));
const rowIndex = rows.findIndex((record) => record.placementId === submissionEnvelope.placementId);
if (rowIndex >= 0) {
persistRecordPatch("placementTable", rows[rowIndex], rowIndex, getPlacementWorkflowPatch(workflowType, activeStepData));
refreshConnectedTableState("placementTable");
}
recordActivity(workflowType, `${form.querySelector(".section-kicker")?.textContent || "Placement workflow"} saved`, `Operation ${submissionEnvelope.workflowId} captured all ${submissionEnvelope.stepCount} workflow steps.`, "Local", { placementId: submissionEnvelope.placementId, workflowId: submissionEnvelope.workflowId });
const timeline = document.querySelector("[data-activity-timeline]");
if (timeline) {
timeline.innerHTML = renderActivityTimelineMarkup();
}
showToast("Stage saved locally", `${form.querySelector(".section-kicker")?.textContent || "Placement stage"} is preserved for ${submissionEnvelope.placementId} in IndexedDB.`, "success");
if (button.dataset.placementSubmit === "remote") {
button.disabled = true;
const result = await submitRemoteOperation(workflowType, submissionEnvelope, `${workflowType} submitted`);
await capturePlacementResponse(result, submissionEnvelope);
button.disabled = false;
if (timeline) {
timeline.innerHTML = renderActivityTimelineMarkup();
}
}
});
});
});
}
async function renderPartnerOperations() {
const workItems = await fetchDataset("partnerOperations");
await Promise.all([fetchDataset("requests"), fetchDataset("cases"), fetchDataset("providers"), fetchDataset("veterans")]);
const effective = getEffectiveDatasourceRows("partnerOperations");
const countType = (type, predicate = () => true) => effective.filter((row) => row.workType === type && predicate(row)).length;
pageContent.innerHTML = `
P1 agent operations Close every handoff after placement begins Provider decisions, SLA tasks, accessible notifications, extension plans, and exceptions share one accountable queue and activity history.
New work item
${p0ControlBanner("Closed-loop operational controls")}
${metricCard("bi bi-building-check", "Provider responses due", String(countType("Provider Response", (row) => row.status !== "Completed")), "Accept or decline with deadline and reason")}
${metricCard("bi bi-alarm", "Escalated SLA work", String(countType("SLA Task", (row) => row.status === "Escalated")), "Overdue tasks needing supervisor attention")}
${metricCard("bi bi-send-exclamation", "Delivery follow-up", String(countType("Event Notification", (row) => row.deliveryStatus !== "Delivered")), "Pending, failed, or retry-scheduled messages")}
${metricCard("bi bi-house-up", "Transition work open", String(countType("Extension & Transition", (row) => row.status !== "Completed")), "Extensions and longer-term housing plans")}
${metricCard("bi bi-exclamation-octagon", "Exceptions unresolved", String(countType("Exception Resolution", (row) => row.status !== "Completed")), "No inventory, declines, missed arrivals, and relocations")}
Operational work queue
Filter by P1 workflow
${[
["", "All work"],
["Provider Response", "Provider responses"],
["SLA Task", "SLA tasks"],
["Event Notification", "Notifications"],
["Extension & Transition", "Extensions & transitions"],
["Exception Resolution", "Exceptions"]
].map(([value, label], index) => `${escapeHtml(label)} ${value ? countType(value) : effective.length} `).join("")}
${renderTableBlock("partnerOperationsTable", workItems, [
{ key: "coordinationId", label: "Work Item" },
{ key: "workType", label: "Workflow" },
{ key: "placementId", label: "Placement" },
{ key: "veteranName", label: "Veteran" },
{ key: "providerName", label: "Provider" },
{ key: "owner", label: "Owner" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "actionDeadline", label: "Deadline", formatter: dateTimeFormatter },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "actionOutcome", label: "Outcome" },
{ key: "nextAction", label: "Next Action" }
], "workType")}
`;
bindRecordButtons();
bindTableInteractions("partnerOperationsTable", workItems);
bindPartnerOperationsActions();
}
function bindPartnerOperationsActions() {
document.querySelector("[data-p1-new]")?.addEventListener("click", () => openNewRecordEditor("partnerOperationsTable"));
const filter = document.querySelector("[data-table-filter='partnerOperationsTable']");
document.querySelectorAll("[data-partner-filter]").forEach((button) => {
button.addEventListener("click", () => {
document.querySelectorAll("[data-partner-filter]").forEach((candidate) => {
const active = candidate === button;
candidate.classList.toggle("active", active);
candidate.setAttribute("aria-selected", String(active));
});
if (filter) {
filter.value = button.dataset.partnerFilter || "";
filter.dispatchEvent(new Event("change", { bubbles: true }));
}
showToast("Queue filtered", button.dataset.partnerFilter ? `Showing ${button.dataset.partnerFilter} work.` : "Showing all agent operations.", "info");
});
});
}
function p0ControlBanner(title) {
return `
${escapeHtml(title)}
Profile-scoped tenant and role context, optimistic record versions, conflict checks, IndexedDB durability, and audit events are active. Remote writes use the centralized API service; this static prototype is not a production identity provider.
`;
}
async function renderVeteran360() {
const veterans = await fetchDataset("veterans");
await Promise.all([fetchDataset("requests"), fetchDataset("providers"), fetchDataset("coordinatedEntry"), fetchDataset("consents")]);
const effective = getEffectiveDatasourceRows("veterans");
pageContent.innerHTML = `
By-name list and master profile One accountable view of each veteran and household Resolve duplicates, confirm eligibility, see active programs, and keep a responsible provider visible across coordinated care.
Add veteran profile
${p0ControlBanner("P0 data controls")}
${metricCard("bi bi-people", "Active by-name list", String(effective.length), "Unified veteran and household records")}
${metricCard("bi bi-exclamation-triangle", "Potential duplicates", String(effective.filter((row) => row.duplicateStatus === "Potential duplicate").length), "Profiles requiring identity resolution")}
${metricCard("bi bi-patch-check", "Eligibility verified", String(effective.filter((row) => row.eligibilityStatus === "Verified").length), "Records ready for program matching")}
${metricCard("bi bi-person-check", "Accountable provider", String(effective.filter((row) => row.responsibleProviderId).length), "Profiles with named service ownership")}
${renderTableBlock("veteranTable", veterans, [
{ key: "veteranId", label: "Veteran ID" },
{ key: "veteranName", label: "Veteran" },
{ key: "householdId", label: "Household" },
{ key: "currentHousing", label: "Housing Status" },
{ key: "eligibilityStatus", label: "Eligibility", formatter: statusPill },
{ key: "activePrograms", label: "Active Program" },
{ key: "responsibleProvider", label: "Responsible Provider" },
{ key: "coordinatedEntryStatus", label: "CE Status", formatter: statusPill },
{ key: "duplicateStatus", label: "Duplicate Review" }
], "coordinatedEntryStatus")}
`;
bindRecordButtons();
bindTableInteractions("veteranTable", veterans);
bindP0PageActions();
}
async function renderCoordinatedEntry() {
const assessments = await fetchDataset("coordinatedEntry");
await Promise.all([fetchDataset("veterans"), fetchDataset("providers")]);
const effective = getEffectiveDatasourceRows("coordinatedEntry");
pageContent.innerHTML = `
Standardized assessment Explainable prioritization and referral decisions Capture housing crisis, vulnerability, program eligibility, recommended priority, supervisor overrides, and referral outcomes in one auditable record.
Start assessment
${p0ControlBanner("Assessment governance")}
${metricCard("bi bi-clipboard2-pulse", "Assessments", String(effective.length), "Standardized coordinated-entry records")}
${metricCard("bi bi-exclamation-diamond", "Critical priority", String(effective.filter((row) => row.finalPriority === "Critical").length), "Highest-priority households")}
${metricCard("bi bi-arrow-repeat", "Referral pending", String(effective.filter((row) => row.status === "Referral Pending").length), "Decisions awaiting closed-loop response")}
${metricCard("bi bi-person-check", "Supervisor review", String(effective.filter((row) => row.status === "Supervisor Review").length), "Overrides requiring accountable review")}
${renderTableBlock("assessmentTable", assessments, [
{ key: "assessmentId", label: "Assessment ID" },
{ key: "veteranId", label: "Veteran ID" },
{ key: "veteranName", label: "Veteran" },
{ key: "housingCrisis", label: "Housing Crisis" },
{ key: "vulnerabilityScore", label: "Score" },
{ key: "programEligibility", label: "Eligibility" },
{ key: "finalPriority", label: "Final Priority", formatter: priorityPill },
{ key: "referralDecision", label: "Referral Decision" },
{ key: "status", label: "Status", formatter: statusPill }
], "status")}
`;
bindRecordButtons();
bindTableInteractions("assessmentTable", assessments);
bindP0PageActions();
}
async function renderAvailabilityBoard() {
const units = await fetchDataset("units");
await Promise.all([fetchDataset("providers"), fetchDataset("cases")]);
const effective = getEffectiveDatasourceRows("units");
const activeHolds = effective.filter((row) => row.status === "Held" && Date.parse(row.holdExpiresAt) > Date.now()).length;
pageContent.innerHTML = `
Real-time placement inventory Bed and unit availability with hold protection Track provider inventory, accessibility, expiring holds, reservations, check-in state, and competing-placement conflicts.
Add bed or unit
${p0ControlBanner("Inventory concurrency controls")}
${metricCard("bi bi-door-open", "Available now", String(effective.filter((row) => row.status === "Available").length), "Units open for matching")}
${metricCard("bi bi-hourglass-split", "Active holds", String(activeHolds), "Unexpired reservation holds")}
${metricCard("bi bi-universal-access", "Accessible inventory", String(effective.filter((row) => row.accessibility !== "Standard" && row.status === "Available").length), "Available accessibility-ready options")}
${metricCard("bi bi-exclamation-octagon", "Conflict review", String(effective.filter((row) => row.conflictStatus !== "Clear").length), "Competing holds requiring action")}
${renderTableBlock("unitTable", units, [
{ key: "unitId", label: "Unit ID" },
{ key: "providerId", label: "Provider ID" },
{ key: "providerName", label: "Provider" },
{ key: "unitType", label: "Unit Type" },
{ key: "county", label: "County" },
{ key: "accessibility", label: "Accessibility" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "holdExpiresAt", label: "Hold Expires", formatter: dateTimeFormatter },
{ key: "conflictStatus", label: "Conflict" }
], "status")}
`;
bindRecordButtons();
bindTableInteractions("unitTable", units);
bindP0PageActions();
}
async function renderConsentCenter() {
const consents = await fetchDataset("consents");
await fetchDataset("veterans");
const effective = getEffectiveDatasourceRows("consents");
pageContent.innerHTML = `
Purpose-bound information sharing Consent, revocation, and disclosure history Record permitted organizations, minimum-necessary data categories, effective dates, signature evidence, revocation, and disclosure activity.
Record consent
${p0ControlBanner("Consent and disclosure controls")}
${metricCard("bi bi-file-earmark-check", "Active consents", String(effective.filter((row) => row.status === "Active").length), "Current purpose-bound permissions")}
${metricCard("bi bi-file-earmark-x", "Revoked", String(effective.filter((row) => row.status === "Revoked").length), "Permissions no longer valid")}
${metricCard("bi bi-pen", "Signatures captured", String(effective.filter((row) => row.signatureStatus === "Captured").length), "Consent evidence retained")}
${metricCard("bi bi-journal-text", "Disclosures logged", String(effective.reduce((total, row) => total + Number(row.disclosureCount || 0), 0)), "Recorded information-sharing events")}
${renderTableBlock("consentTable", consents, [
{ key: "consentId", label: "Consent ID" },
{ key: "veteranId", label: "Veteran ID" },
{ key: "veteranName", label: "Veteran" },
{ key: "permittedOrganization", label: "Permitted Organization" },
{ key: "informationCategories", label: "Information Categories" },
{ key: "purpose", label: "Purpose" },
{ key: "expirationDate", label: "Expires" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "disclosureCount", label: "Disclosures" }
], "status")}
`;
bindRecordButtons();
bindTableInteractions("consentTable", consents);
bindP0PageActions();
}
function bindP0PageActions() {
document.querySelectorAll("[data-p0-new]").forEach((button) => {
button.addEventListener("click", () => openNewRecordEditor(button.dataset.p0New));
});
}
function renderVersionHistory() {
const releases = [
{
version: "0.11.0",
date: "October 3, 2026",
status: "Current prototype",
tone: "text-bg-primary",
title: "Validation, scenario data, and release traceability",
summary: "Added cross-workflow validation, operational readiness summaries, scenario-linked South Jersey datasets, repairable provider fields, and a governed application history.",
evidence: ["5,124 scenario-linked records", "12 operational pages plus version history", "Hosted endpoint and browser regression checks"],
current: true
},
{
version: "0.10.0",
date: "October 3, 2026",
status: "Superseded",
tone: "text-bg-secondary",
title: "Operational quality controls",
summary: "Introduced freshness, relationship, chronology, consent, inventory, and partner-outcome checks across the shared modal and data-validation layers.",
evidence: ["Fourteen-day operational data window", "Scenario and quality metadata", "Relationship integrity validation"]
},
{
version: "0.9.0",
date: "October 1, 2026",
status: "Documented baseline",
tone: "text-bg-success",
title: "Local-first coordinated-care prototype",
summary: "Established the published multi-page portal, profile-scoped local workspace, linked records, editable modal tabs, hosted data feeds, and the documented end-to-end veteran journey.",
evidence: ["Canonical Xenhey page inventory", "LocalStorage and IndexedDB continuity", "README user-journey evidence"]
},
{
version: "0.5.0",
date: "September 2026",
status: "Design milestone",
tone: "text-bg-secondary",
title: "Connected workflow expansion",
summary: "Expanded intake, provider, case, agent placement, Veteran 360, coordinated entry, consent, availability, agent operations, and reporting into one navigable experience.",
evidence: ["Six-step placement journey", "Connected record editing", "Responsive shared navigation"]
},
{
version: "0.1.0",
date: "June 27, 2026",
status: "Discovery milestone",
tone: "text-bg-secondary",
title: "Delivery and research foundation",
summary: "Captured the initial delivery plan, opportunity research, readiness inputs, pricing considerations, and bid decision structure that informed the care-coordination prototype.",
evidence: ["Delivery-plan baseline", "Research and intake artifacts", "Three-year readiness framing"]
}
];
const roadmap = [
["1.0.0", "Governed pilot", "Planned", "Validate service journeys with representative users; establish identity, tenant, consent, audit, API-contract, accessibility, and support readiness gates."],
["1.1.0", "Coherent workflow slices", "Planned", "Deliver production intake, Veteran 360, assessment, consent, matching, and placement slices against versioned contracts and authoritative data ownership."],
["2.0.0", "Controlled production service", "Future gate", "Promote only after resilience, security, privacy, migration, observability, rollback, agent operations, and limited-pilot evidence are approved."]
];
pageContent.innerHTML = `
Application record
A traceable history of what changed, why it changed, and what remains planned
This registry follows From Urgent Request to Stable Housing , especially Chapters 9, 11, and 12. It separates delivered prototype evidence from future production commitments.
Current v0.11.0 Prototype track
${insightCard("Release track", "Prototype", "A validated learning asset, not a production trust boundary")}
${insightCard("Current version", "0.11.0", "Scenario validation and application history")}
${insightCard("Reference", "Ch. 9, 11, 12", "Local-first trust, production boundary, and roadmap")}
${insightCard("Promotion rule", "Evidence first", "Accessibility, integrity, security, and operations are release gates")}
Delivered history Prototype milestones Dates reflect documented project milestones. Earlier entries are curated capability baselines rather than claims of production deployment.
${releases.map((release) => `
v${release.version} ${release.status} ${release.date}
${release.title} ${release.summary}
${release.evidence.map((item) => `${item} `).join("")}
`).join("")}
Not yet released PDF-derived production roadmap These versions are planning labels. They do not indicate production approval or deployment.
Roadmap only
${roadmap.map(([version, title, status, summary]) => `
${status} v${version} ${title} ${summary}
`).join("")}
Minimum release record Evidence required for every future version
${storyCard("bi bi-fingerprint", "Identity and source", "Release owner, actor, organization, authoritative source, correlation ID, and approval evidence.")}
${storyCard("bi bi-code-square", "Contract and version", "Application version, schema and rule versions, expected record version, migration notes, and compatibility boundary.")}
${storyCard("bi bi-shield-check", "Trust and readiness", "Security, privacy, accessibility, data quality, resilience, observability, rollback, and support evidence.")}
${storyCard("bi bi-clock-history", "Time and outcome", "Effective time, deployment time, synchronization state, conflict resolution, measured outcome, and known limitations.")}
`;
}
async function renderServiceOperations() {
const dataKeys = Object.keys(dataUrls);
await Promise.all(dataKeys.map((key) => fetchDataset(key)));
const allRecords = dataKeys.flatMap((key) => getEffectiveDatasourceRows(key));
const qualityReady = allRecords.filter((record) => record.dataQualityStatus === "Ready").length;
const freshRecords = allRecords.filter((record) => Date.now() - Date.parse(record.lastInventoryCheck || record.updatedAt || record.createdAt || 0) <= 24 * 60 * 60 * 1000).length;
const activity = getActivityHistory();
const incidents = activity.filter((entry) => ["Failed", "Conflict", "Blocked"].includes(entry.status));
const qualityRate = allRecords.length ? (qualityReady / allRecords.length) * 100 : 0;
const freshnessRate = allRecords.length ? (freshRecords / allRecords.length) * 100 : 0;
const sloCards = [
["Data quality", `${qualityRate.toFixed(1)}%`, qualityRate >= 95 ? "Within target" : "Review required", "95% records marked ready"],
["Freshness", `${freshnessRate.toFixed(1)}%`, freshnessRate >= 80 ? "Within target" : "Review required", "80% updated within 24 hours"],
["Operational exceptions", String(incidents.length), incidents.length === 0 ? "Within target" : "Action required", "No unresolved failed, blocked, or conflicted activity"],
["Dataset availability", `${dataKeys.length}/${dataKeys.length}`, "Within target", "All published operational feeds loaded"]
];
const integrationLabels = { requests: "Veteran requests", providers: "Provider network", cases: "Case management", reports: "Reporting", veterans: "Veteran 360", coordinatedEntry: "Coordinated entry", consents: "Consent center", units: "Bed and unit inventory", partnerOperations: "Agent operations" };
const integrations = dataKeys.map((key) => ({ name: integrationLabels[key] || key, status: tableStore[key]?.length ? "Available" : "Unavailable", evidence: `${tableStore[key]?.length || 0} records loaded`, owner: key === "consents" ? "Privacy Operations" : key === "reports" ? "Program Analytics" : "Care Operations" }));
const gates = [
["Data integrity", qualityRate >= 95, "Relationships, required values, provenance, and quality status"],
["Synchronization", true, "Local, queued, submitted, accepted, rejected, and conflict states are explicit"],
["Accessibility", true, "Labels, keyboard controls, mobile geometry, typeahead, and responsive tables"],
["Resilience", true, "Local persistence, IndexedDB mirror, retry queue, timeout, and complete clear workflow"],
["Production identity", false, "Requires external identity provider and server-side authorization"],
["Protected service secrets", false, "Requires a trusted backend gateway; static hosting is not sufficient"],
["Authoritative audit", false, "Requires immutable server-side audit storage and retention policy"],
["Controlled pilot", false, "Requires representative users, staffed support, measures, and stop conditions"]
];
pageContent.innerHTML = `
P2 service assurance Operational health connected to care impact This prototype calculates readiness from published sample data and local activity. It does not replace production telemetry, incident management, or authoritative audit.
Run readiness check
${sloCards.map(([label, value, status, note]) => insightCard(label, value, `${status} - ${note}`)).join("")}
Integrations
Incidents ${incidents.length}
Simulations
Release gates
${integrations.map((item) => `
${escapeHtml(item.name)} ${item.status}
${escapeHtml(item.evidence)}
Owner: ${escapeHtml(item.owner)} `).join("")}
${incidents.length ? `
${incidents.slice(0, 25).map((item) => `
${escapeHtml(item.title)} ${escapeHtml(item.status)}
${escapeHtml(item.details)}
${dateTimeFormatter(item.occurredAt)} - Owner: ${escapeHtml(item.actor || "Unassigned")} `).join("")}
` : `
No failed, blocked, or conflicted local activities are currently recorded.
`}
${[
["network-loss", "Network interruption", "Verify local save, retry queue, and honest synchronization state."],
["version-conflict", "Concurrent update", "Verify stale updates are blocked and both versions remain reviewable."],
["provider-failure", "Provider decline", "Verify hold release, alternate routing, notification, and ownership."],
["consent-revocation", "Consent revocation", "Verify future disclosure stops while prior events remain auditable."],
["accessibility", "Accessible journey", "Verify keyboard, screen-reader, zoom, touch, and alternate-channel paths."],
["recovery", "Backup and recovery", "Verify profile cache, IndexedDB, export, deletion, and session recovery behavior."],
["quota", "Storage quota exhaustion", "Verify quota errors are explicit and no remote-success claim is made."],
["multi-tab", "Concurrent browser tabs", "Verify BroadcastChannel change notices and optimistic version checks prevent silent overwrite."],
["migration", "IndexedDB schema migration", "Verify the v2 database opens, retains entries, and reports its active schema version."],
["partial-failure", "Partial remote failure", "Verify the local record, stable operation identity, queue item, retry action, and receipt linkage remain consistent."]
].map(([key, title, note]) => `
${title} ${note}
Record simulation `).join("")}
${gates.map(([name, passed, evidence], gateIndex) => `
${passed ? "Evidence present" : gateIndex < 4 ? "Action required" : "External capability required"} `).join("")}
`;
pageContent.querySelector("[data-readiness-check]")?.addEventListener("click", () => {
recordActivity("readiness-check", "P2 readiness check completed", `${gates.filter((gate) => gate[1]).length} of ${gates.length} prototype gates have evidence.`, "Completed", { passed: gates.filter((gate) => gate[1]).length, total: gates.length });
showToast("Readiness check complete", `${gates.filter((gate) => gate[1]).length} of ${gates.length} gates have prototype evidence.`, "success");
});
pageContent.querySelectorAll("[data-run-simulation]").forEach((button) => button.addEventListener("click", () => {
const simulation = button.dataset.runSimulation;
recordActivity("operational-simulation", "Operational simulation recorded", `${simulation} was recorded as a prototype rehearsal requiring reviewer evidence.`, "Completed", { simulation });
button.textContent = "Simulation recorded";
button.classList.replace("btn-outline-primary", "btn-success");
showToast("Simulation recorded", "The rehearsal is saved in the local activity history.", "success");
}));
}
async function renderAssuranceWorkbench() {
const controls = await fetchDataset("assuranceControls");
const effectiveControls = getEffectiveDatasourceRows("assuranceControls");
const countStatus = (status) => effectiveControls.filter((control) => control.implementationStatus === status).length;
const chapterCount = new Set(effectiveControls.map((control) => control.chapter)).size;
const evidenceCount = effectiveControls.filter((control) => control.evidenceState === "Available").length;
pageContent.innerHTML = `
Reflection-to-delivery register All 102 requirements in one accountable workspace This register converts the book's reflection questions into owned implementation controls. Prototype evidence is not production certification, and external capabilities remain explicitly unresolved.
${chapterCount} chapters
${insightCard("Total controls", String(effectiveControls.length), "Every reflection question has a stable control ID")}
${insightCard("Prototype evidence", String(countStatus("Prototype evidence present")), "Implemented or evidenced in the current demonstration")}
${insightCard("Action required", String(countStatus("Action required")), "Workflow or representative-user evidence remains")}
${insightCard("External capability", String(countStatus("External capability required")), "Requires trusted services, policy approval, or staffed operations")}
${insightCard("Evidence available", String(evidenceCount), "Controls linked to current prototype evidence")}
Trust boundary Local edits support planning and rehearsal. Production approval requires authoritative identity, server authorization, protected secrets, immutable audit, approved policy, operational ownership, and representative-user evidence.
${renderTableBlock("assuranceControlTable", controls, [
{ key: "controlId", label: "Control ID" },
{ key: "chapter", label: "Chapter" },
{ key: "requirement", label: "Implementation Requirement" },
{ key: "implementationStatus", label: "Status", formatter: statusPill },
{ key: "owner", label: "Owner" },
{ key: "evidenceState", label: "Evidence", formatter: statusPill },
{ key: "reviewCadence", label: "Review Cadence" }
], "implementationStatus")}
`;
bindRecordButtons();
bindTableInteractions("assuranceControlTable", controls);
}
async function renderReports() {
const [reports] = await Promise.all([
fetchDataset("reports"),
fetchDataset("requests"),
fetchDataset("cases"),
fetchDataset("providers")
]);
const effectiveRequests = getEffectiveDatasourceRows("requests");
const effectiveCases = getEffectiveDatasourceRows("cases");
const effectiveProviders = getEffectiveDatasourceRows("providers");
const operationalKpis = calculateOperationalKpis(effectiveRequests, effectiveCases);
const kpiGovernance = calculateKpiGovernance(reports, effectiveRequests, effectiveCases, effectiveProviders, operationalKpis);
const kpiDefinitions = buildKpiDefinitions(kpiGovernance, operationalKpis);
pageContent.innerHTML = `
Funding and utilization
Program reporting designed for agencies, nonprofits, and internal leadership
Track requests, placements, average response times, active stays, provider utilization, and cost by region.
Export monthly snapshot
${insightCard("Total report rows", String(reports.length), "Published monthly-region records available for export")}
${insightCard("Average placement time", averageNumber(reports, "averageHours"), "Calculated from the hosted reporting feed")}
${insightCard("Highest active stays", String(Math.max(...reports.map((row) => row.activeStays))), "Peak regional active stay count")}
${insightCard("Typical utilization", dominantValue(reports, "utilizationRate"), "Most common utilization value in this sample set")}
${insightCard("Time to confirmed placement", `${operationalKpis.averagePlacementHours.toFixed(1)} hrs`, `${operationalKpis.periodLabel}; created to assigned or latest placement event`)}
${insightCard("Extensions", String(operationalKpis.extensions), `${operationalKpis.periodLabel}; cases with extensionRequested = true`)}
${insightCard("Unsuccessful matches", String(operationalKpis.unsuccessfulMatches), `${operationalKpis.periodLabel}; declined, no inventory, or unsuccessful case events`)}
Governed KPI framework Decision-ready measures with stable definitions Each KPI declares its calculation, grain, time boundary, exclusions, source, owner, target, and balancing measures so results remain interpretable.
Definition v1.1 Run 12-step validation
${kpiDefinitions.map((kpi, index) => `${escapeHtml(kpi.name)} ${escapeHtml(kpi.value)} `).join("")}
${kpiDefinitions.map((kpi, index) => `
${renderKpiDefinition(kpi)}
`).join("")}
${renderTableBlock("reportTable", reports, [
{ key: "reportId", label: "Report ID" },
{ key: "month", label: "Month" },
{ key: "region", label: "Region" },
{ key: "requests", label: "Requests" },
{ key: "placements", label: "Placements" },
{ key: "averageHours", label: "Avg Hours" },
{ key: "activeStays", label: "Active Stays" },
{ key: "cost", label: "Cost" }
], "region")}
`;
bindRecordButtons();
bindTableInteractions("reportTable", reports);
pageContent.querySelector("[data-kpi-validate]")?.addEventListener("click", () => {
const checks = kpiDefinitions.flatMap((kpi) => kpi.checks);
const passed = checks.filter((check) => check.status === "Pass").length;
const actionRequired = checks.length - passed;
recordActivity("kpi-validation", "KPI governance validation completed", `${passed} of ${checks.length} checks passed; ${actionRequired} require review.`, actionRequired ? "Review" : "Completed", { passed, actionRequired, definitionVersion: "1.1" });
showToast("KPI validation complete", `${passed} of ${checks.length} checks passed. ${actionRequired} require review.`, actionRequired ? "warning" : "success");
});
}
function calculateKpiGovernance(reports, requests, cases, providers, operationalKpis) {
const now = Date.now();
const freshnessCutoff = now - (24 * 60 * 60 * 1000);
const lateCutoff = now - (14 * 24 * 60 * 60 * 1000);
const totalRequests = reports.reduce((total, row) => total + Number(row.requests || 0), 0);
const totalPlacements = reports.reduce((total, row) => total + Number(row.placements || 0), 0);
const freshProviders = providers.filter((provider) => new Date(provider.lastInventoryCheck || 0).getTime() >= freshnessCutoff).length;
const requiredFields = [
[reports, ["reportId", "month", "region", "requests", "placements", "updatedAt"]],
[requests, ["id", "veteran", "status", "createdAt", "updatedAt"]],
[cases, ["caseId", "requestId", "veteran", "status", "updatedAt"]],
[providers, ["providerId", "name", "county", "status", "updatedAt"]]
];
let requiredValues = 0;
let completedValues = 0;
requiredFields.forEach(([rows, fields]) => rows.forEach((row) => fields.forEach((field) => {
requiredValues += 1;
if (row[field] !== undefined && row[field] !== null && String(row[field]).trim() !== "") completedValues += 1;
})));
const duplicateCount = (rows, key) => rows.length - new Set(rows.map((row) => row[key]).filter(Boolean)).size;
const requestIds = new Set(requests.map((request) => request.id));
const orphanCases = cases.filter((caseRecord) => !requestIds.has(caseRecord.requestId)).length;
const lateRecords = [...reports, ...requests, ...cases, ...providers].filter((record) => {
const timestamp = new Date(record.updatedAt || record.createdAt || 0).getTime();
return !Number.isFinite(timestamp) || timestamp < lateCutoff;
}).length;
const openRequests = requests.filter((request) => !["Closed", "Completed", "Cancelled"].includes(request.status)).length;
const invalidDurations = cases.filter((caseRecord) => {
const request = requests.find((item) => item.id === caseRecord.requestId);
const start = new Date(request?.createdAt || 0).getTime();
const end = new Date(caseRecord.updatedAt || caseRecord.createdAt || 0).getTime();
return Number.isFinite(start) && Number.isFinite(end) && end < start;
}).length;
const invalidAggregates = reports.filter((row) => Number(row.placements || 0) > Number(row.requests || 0) || Number(row.requests || 0) < 0).length;
const duplicateKeys = duplicateCount(reports, "reportId") + duplicateCount(requests, "id") + duplicateCount(cases, "caseId") + duplicateCount(providers, "providerId");
const qualityRate = requiredValues ? (completedValues / requiredValues) * 100 : 0;
return {
placementRate: totalRequests ? (totalPlacements / totalRequests) * 100 : 0,
totalRequests,
totalPlacements,
freshnessRate: providers.length ? (freshProviders / providers.length) * 100 : 0,
freshProviders,
qualityRate,
duplicateKeys,
orphanCases,
invalidDurations,
invalidAggregates,
lateRecords,
openRequests,
reportSegments: buildProtectedKpiSegments(reports, "region", (rows) => ({
denominator: rows.reduce((total, row) => total + Number(row.requests || 0), 0),
value: rows.reduce((total, row) => total + Number(row.placements || 0), 0),
format: (value, denominator) => `${denominator ? ((value / denominator) * 100).toFixed(1) : "0.0"}%`
})),
durationSegments: buildDurationSegments(requests, cases),
freshnessSegments: buildProtectedKpiSegments(providers, "county", (rows) => ({
denominator: rows.length,
value: rows.filter((provider) => new Date(provider.lastInventoryCheck || 0).getTime() >= freshnessCutoff).length,
format: (value, denominator) => `${denominator ? ((value / denominator) * 100).toFixed(1) : "0.0"}%`
})),
periodLabel: operationalKpis.periodLabel
};
}
function buildProtectedKpiSegments(rows, key, summarize) {
const groups = new Map();
rows.forEach((row) => {
const label = String(row[key] || "Unspecified");
if (!groups.has(label)) groups.set(label, []);
groups.get(label).push(row);
});
return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([label, groupRows]) => {
const summary = summarize(groupRows);
return {
label,
denominator: summary.denominator,
result: summary.format(summary.value, summary.denominator),
protected: summary.denominator < 5
};
});
}
function buildDurationSegments(requests, cases) {
const requestMap = new Map(requests.map((request) => [request.id, request]));
const groups = new Map();
cases.forEach((caseRecord) => {
const request = requestMap.get(caseRecord.requestId);
const start = new Date(request?.createdAt || 0).getTime();
const end = new Date(caseRecord.updatedAt || caseRecord.createdAt || 0).getTime();
if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return;
const label = String(request.priority || "Unspecified");
if (!groups.has(label)) groups.set(label, []);
groups.get(label).push((end - start) / 3600000);
});
return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([label, durations]) => ({
label,
denominator: durations.length,
result: `${(durations.reduce((total, value) => total + value, 0) / durations.length).toFixed(1)} hrs`,
protected: durations.length < 5
}));
}
function buildKpiDefinitions(governance, operationalKpis) {
const qualityStatus = `${governance.qualityRate.toFixed(1)}% required-field completeness; ${governance.lateRecords} late or stale records`;
const common = {
openLate: `${governance.openRequests} open requests remain in live operational counts. Late arrivals are accepted for 14 days, trigger a restatement, and remain labeled preliminary until the window closes; ${governance.lateRecords} currently fall outside policy.`,
joinControl: `Primary keys are checked before joins. Current audit: ${governance.duplicateKeys} duplicate keys, ${governance.orphanCases} orphan cases, and ${governance.invalidAggregates} invalid report aggregates.`,
qualityIndicator: qualityStatus,
qualityScore: `${governance.qualityRate.toFixed(1)}%`,
privacy: "Role-scoped operational access; public or shared segment cells below five eligible observations are suppressed and direct identifiers are excluded.",
version: "v1.1; effective October 4, 2026; changes require owner approval and a documented rationale."
};
const definitions = [
{
...common,
name: "Confirmed Placement Rate", value: `${governance.placementRate.toFixed(1)}%`, observationCount: governance.totalRequests,
purpose: "Supports monthly capacity, staffing, and escalation decisions; falling below target opens a regional placement recovery review.",
grain: "One monthly-region reporting observation, aggregated from eligible veteran requests.",
numerator: `${governance.totalPlacements} confirmed placements in eligible reporting rows.`, denominator: `${governance.totalRequests} eligible veteran requests in the same rows.`,
events: "Start: eligible request received. End: placement confirmed or assigned.", window: "Event-period, current published calendar month by region.",
exclusions: "Cancelled, duplicate, test, and administratively withdrawn requests are excluded before aggregation.",
segments: "Region, priority, household type, accessibility need, and funding source.", sources: "reports.requests and reports.placements, reconciled to request and case primary keys.",
owner: "Definition: Program Analytics. Target: Program Director. Response action: Care Operations Lead.",
target: ">= 85% monthly. Below 85% opens regional recovery review; below 75% requires executive escalation. Targets remain provisional until pilot approval.",
balancing: "Unsuccessful matches, preference overrides, inappropriate-placement review, and seven-day re-placement.", segmentRows: governance.reportSegments
},
{
...common,
name: "Time to Confirmed Placement", value: `${operationalKpis.averagePlacementHours.toFixed(1)} hrs`, observationCount: operationalKpis.placedCount || governance.totalPlacements,
purpose: "Supports daily staffing and escalation decisions; threshold breaches trigger queue and provider-response review.",
grain: "One eligible request that reaches an assigned or confirmed placement event.",
numerator: "Sum of elapsed placement hours across eligible requests.", denominator: "Requests with valid start and end timestamps.",
events: "Start: requests.createdAt. End: assignedAt, confirmed placement event, or latest eligible placement case event.", window: `${governance.periodLabel}; rolling operational event-period view.`,
exclusions: "Cancelled, duplicate, test, missing-timestamp, and negative-duration records are excluded and counted in quality evidence.",
segments: "Priority, county, request type, accessibility need, provider, and case manager.", sources: "requests.createdAt joined to cases.requestId and eligible placement timestamps.",
owner: "Definition: Care Operations Analytics. Target: Care Operations Director. Response action: Case Review Lead.",
target: "<= 24 hours overall and <= 4 hours for critical requests. Breach triggers same-day queue review; provisional pilot target.",
balancing: "Placement appropriateness, consent, accessibility fit, declines, and re-placement within seven days.", segmentRows: governance.durationSegments
},
{
...common,
name: "Provider Inventory Freshness", value: `${governance.freshnessRate.toFixed(1)}%`, observationCount: governance.freshProviders,
purpose: "Supports real-time matching confidence; a breach triggers provider outreach and prevents stale inventory from being presented as ready.",
grain: "One active provider inventory record at report run time.",
numerator: `${governance.freshProviders} providers confirmed within 24 hours.`, denominator: "Active providers eligible for matching.",
events: "Start: provider inventory confirmation. End: report run timestamp.", window: "Rolling 24-hour point-in-time measure.",
exclusions: "Inactive, suspended, duplicate, and onboarding-only provider records are excluded.",
segments: "County, provider type, accessibility capability, and availability status.", sources: "providers.lastInventoryCheck and providers.status at the current effective version.",
owner: "Definition: Provider Analytics. Target: Network Director. Response action: Provider Success Lead.",
target: ">= 95% daily. Below 95% opens provider outreach; below 85% blocks stale inventory from automated matching.",
balancing: "Inventory conflicts, rejected placements, false availability, and synchronization errors.", segmentRows: governance.freshnessSegments
}
];
return definitions.map((definition) => ({ ...definition, checks: buildKpiChecks(definition, governance) }));
}
function buildKpiChecks(kpi, governance) {
const result = (step, label, passed, evidence) => ({ step, label, status: passed ? "Pass" : "Action required", evidence });
return [
result(1, "Decision and action", Boolean(kpi.purpose && kpi.target), `${kpi.purpose} ${kpi.target}`),
result(2, "Observation grain", Boolean(kpi.grain && kpi.observationCount >= 0), `${kpi.grain} Current observations: ${kpi.observationCount}.`),
result(3, "Calculation and exclusions", Boolean(kpi.numerator && kpi.denominator && kpi.exclusions), `${kpi.numerator} Denominator: ${kpi.denominator} Exclusions: ${kpi.exclusions}`),
result(4, "Time model", /event-period|rolling|point-in-time|cohort/i.test(kpi.window), kpi.window),
result(5, "Open and late records", governance.lateRecords === 0, kpi.openLate),
result(6, "Duration events", governance.invalidDurations === 0, `${kpi.events} Invalid negative durations: ${governance.invalidDurations}.`),
result(7, "Join integrity", governance.duplicateKeys === 0 && governance.orphanCases === 0 && governance.invalidAggregates === 0, kpi.joinControl),
result(8, "Data-quality indicator", governance.qualityRate >= 95, kpi.qualityIndicator),
result(9, "Approved segments", kpi.segmentRows.length > 0, `${kpi.segments} ${kpi.segmentRows.length} protected segment rows produced.`),
result(10, "Balancing measures", Boolean(kpi.balancing), kpi.balancing),
result(11, "Privacy and small-cell protection", Boolean(kpi.privacy), `${kpi.privacy} ${kpi.segmentRows.filter((row) => row.protected).length} cells suppressed.`),
result(12, "Metric accountability", /Definition:.*Target:.*Response action:/i.test(kpi.owner), `${kpi.owner} ${kpi.version}`)
];
}
function renderKpiDefinition(kpi) {
const rows = [
["Name", kpi.name], ["Purpose", kpi.purpose], ["Grain", kpi.grain], ["Numerator", kpi.numerator],
["Denominator", kpi.denominator], ["Start and end events", kpi.events], ["Window", kpi.window],
["Open and late records", kpi.openLate], ["Exclusions", kpi.exclusions], ["Join controls", kpi.joinControl],
["Data-quality indicator", kpi.qualityIndicator], ["Segments", kpi.segments], ["Sources", kpi.sources],
["Privacy and small cells", kpi.privacy], ["Owners", kpi.owner], ["Target and action", kpi.target],
["Balancing measures", kpi.balancing], ["Definition version", kpi.version]
];
return `
${insightCard("Current value", kpi.value, kpi.target)}
${insightCard("Data quality", kpi.qualityScore, kpi.qualityIndicator)}
${insightCard("Observation count", String(kpi.observationCount), kpi.grain)}
Element Description ${rows.map(([element, description]) => `${escapeHtml(element)} ${escapeHtml(description)} `).join("")}
Executable validation ${kpi.checks.map((check) => `
${check.step}. ${escapeHtml(check.label)} ${escapeHtml(check.evidence)}
${escapeHtml(check.status)} `).join("")}
Protected segment view Cells with fewer than five eligible observations are suppressed.
Segment Eligible Result ${kpi.segmentRows.map((segment) => `${escapeHtml(segment.label)} ${segment.protected ? "Protected " : escapeHtml(String(segment.denominator))} ${segment.protected ? "Suppressed " : escapeHtml(segment.result)} `).join("")}
`;
}
function renderTableBlock(tableId, rows, columns, filterKey) {
const metadataKeys = new Set(["scenarioType", "dataQualityStatus", "updatedAt"]);
const displayColumns = columns.filter((column) => !metadataKeys.has(column.key));
displayColumns.push({ key: "updatedAt", label: "Context", formatter: (_, row) => formatTableContext(row) });
const effectiveRows = resolveTableRows(tableId, rows, displayColumns);
tableSourceRows[tableId] = {
hostedRows: cloneRows(rows),
rows: effectiveRows
};
const filterOptions = [...new Set(effectiveRows.map((row) => row[filterKey]).filter((value) => value !== undefined && value !== ""))];
return `
Edit record
${displayColumns.map((column) => `
${escapeHtml(column.label)}
`).join("")}
${effectiveRows.map((row, index) => renderRow(row, displayColumns, tableId, index)).join("")}
`;
}
function formatTableContext(row) {
const source = row.sourceSystem || (row.__localRecordId || row.__localOverride ? "Local" : "Hosted");
const sync = row.syncStatus || (row.__localRecordId || row.__localOverride ? "Local only" : "Published");
const scenario = row.scenarioType ? `${escapeHtml(row.scenarioType)} ` : "";
const scenarioFamily = row.scenarioFamily ? `${escapeHtml(row.scenarioFamily)}${row.scenarioVariant ? ` / ${escapeHtml(row.scenarioVariant)}` : ""} ` : "";
const quality = row.dataQualityStatus ? `${escapeHtml(row.dataQualityStatus)} ` : "";
const updated = row.updatedAt ? `${escapeHtml(dateTimeFormatter(row.updatedAt))} ` : "";
return `${escapeHtml(source === "Profile-local workspace" ? "Local" : source)} ${scenarioFamily}${scenario}${quality}${updated}
`;
}
function cloneRows(rows) {
return Array.isArray(rows) ? rows.map((row) => ({ ...row })) : [];
}
function getLocalTableStorageKey(tableId) {
const aliases = {
homeRequests: "requests",
requestTable: "requests"
};
return `table:${aliases[tableId] || tableId}`;
}
function readLocalTableState(tableId) {
if (!activeProfile) {
return { addedRecords: [], updates: {} };
}
return storageService.readProfile(activeProfile.profileId, getLocalTableStorageKey(tableId), {
addedRecords: [],
updates: {}
});
}
function writeLocalTableState(tableId, state) {
storageService.writeProfile(activeProfile.profileId, getLocalTableStorageKey(tableId), state);
}
function getRecordIdentity(row, columns, fallbackIndex) {
if (row?.__sourceRecordIdentity) {
return row.__sourceRecordIdentity;
}
const identityColumn = columns.find((column) => /(^id$|id$|key$)/i.test(column.key)) || columns[0];
const identityValue = identityColumn ? row[identityColumn.key] : "";
return `${identityColumn ? identityColumn.key : "row"}:${identityValue || fallbackIndex}`;
}
function resolveTableRows(tableId, hostedRows, columns) {
const state = readLocalTableState(tableId);
const mergedHostedRows = cloneRows(hostedRows).map((row, index) => {
const identity = getRecordIdentity(row, columns, index);
return state.updates[identity] ? { ...row, ...state.updates[identity], __localOverride: true } : row;
});
return [...cloneRows(state.addedRecords), ...mergedHostedRows];
}
const generatedIdDefinitions = {
homeRequests: { key: "id", prefix: "REQ-", width: 6, start: 26000 },
requestTable: { key: "id", prefix: "REQ-", width: 6, start: 26000 },
providerTable: { key: "providerId", prefix: "PROV-", width: 6, start: 9000 },
caseTable: { key: "caseId", prefix: "CASE-", width: 6, start: 11000 },
reportTable: { key: "reportId", prefix: "REP-", width: 6, start: 12000 },
placementTable: { key: "placementId", prefix: "PLC-", width: 6, start: 11000 },
veteranTable: { key: "veteranId", prefix: "VET-", width: 6, start: 30000 },
assessmentTable: { key: "assessmentId", prefix: "CEA-", width: 6, start: 40000 },
consentTable: { key: "consentId", prefix: "CNS-", width: 6, start: 50000 },
unitTable: { key: "unitId", prefix: "UNIT-", width: 6, start: 60000 },
partnerOperationsTable: { key: "coordinationId", prefix: "P1-", width: 6, start: 70000 },
assuranceControlTable: { key: "controlId", prefix: "BRC-CTRL-", width: 6, start: 103 }
};
function generateNextRecordId(rows, definition) {
const escapedPrefix = definition.prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`^${escapedPrefix}(\\d+)$`, "i");
const numbers = rows.map((row) => {
const match = String(row[definition.key] || "").match(pattern);
return match ? Number(match[1]) : NaN;
}).filter(Number.isFinite);
const highest = numbers.length ? Math.max(...numbers) : definition.start - 1;
return `${definition.prefix}${String(Math.max(definition.start, highest + 1)).padStart(definition.width, "0")}`;
}
function getRowsForIdGeneration(tableId) {
const sourceTableId = tableId === "homeRequests" ? "requestTable" : tableId;
const definition = generatedIdDefinitions[sourceTableId];
const candidates = [];
const registryRows = tableRegistry[sourceTableId]?.rows || tableRegistry[tableId]?.rows;
if (Array.isArray(registryRows)) candidates.push(...registryRows);
const sourceRows = tableSourceRows[sourceTableId]?.rows || tableSourceRows[tableId]?.rows;
if (Array.isArray(sourceRows)) candidates.push(...sourceRows);
candidates.push(...cloneRows(readLocalTableState(sourceTableId).addedRecords));
const datasource = tableDatasources[sourceTableId];
if (datasource && dataUrls[datasource]) candidates.push(...getEffectiveDatasourceRows(datasource));
if (sourceTableId === "placementTable") {
(tableStore.cases || []).forEach((record) => candidates.push({ placementId: `PLC-${String(record.caseId || "").replace(/^CASE-/, "")}` }));
(tableStore.partnerOperations || []).forEach((record) => candidates.push({ placementId: record.placementId }));
(tableStore.units || []).forEach((record) => candidates.push({ placementId: record.placementId }));
}
if (!definition) return candidates;
const seen = new Set();
return candidates.filter((record) => {
const value = String(record?.[definition.key] || "");
if (!value || seen.has(value)) return false;
seen.add(value);
return true;
});
}
function buildGeneratedRecordIds(tableId) {
const definition = generatedIdDefinitions[tableId];
if (!definition) {
return {};
}
const rows = getRowsForIdGeneration(tableId);
const generated = { [definition.key]: generateNextRecordId(rows, definition) };
if (tableId === "requestTable" || tableId === "homeRequests") {
generated.customerReferenceNo = generateNextRecordId(rows, {
key: "customerReferenceNo",
prefix: "CRN-",
width: 6,
start: 470000
});
}
if (tableId === "veteranTable") {
generated.householdId = generateNextRecordId(rows, {
key: "householdId",
prefix: "HH-",
width: 6,
start: 18000
});
}
return generated;
}
async function refreshBeforeIdGeneration(tableId) {
const sourceTableId = tableId === "homeRequests" ? "requestTable" : tableId;
const dataKey = tableDatasources[sourceTableId];
const refreshKeys = sourceTableId === "placementTable"
? ["cases", "partnerOperations", "units"]
: dataKey && dataUrls[dataKey] ? [dataKey] : [];
if (!refreshKeys.length) return;
const refreshed = await Promise.all(refreshKeys.map((key) => fetchDataset(key, { forceRefresh: true })));
if (sourceTableId === "placementTable") return;
const hostedRows = refreshed[0];
const columns = getTableColumns(sourceTableId);
const effectiveRows = resolveTableRows(sourceTableId, hostedRows, columns);
tableSourceRows[sourceTableId] = {
hostedRows: cloneRows(hostedRows),
rows: effectiveRows
};
if (tableRegistry[sourceTableId]) {
tableRegistry[sourceTableId].hostedRows = cloneRows(hostedRows);
tableRegistry[sourceTableId].rows = effectiveRows;
tableRegistry[sourceTableId].sortState = { key: null, direction: "ascending" };
rerenderTable(sourceTableId);
}
}
function getRecordPrimaryKey(tableId, record) {
const sourceTableId = tableId === "homeRequests" ? "requestTable" : tableId;
const definition = generatedIdDefinitions[sourceTableId];
if (!definition) {
return null;
}
let value = String(record?.[definition.key] || "").trim();
if (!value && record) {
value = String(buildGeneratedRecordIds(sourceTableId)[definition.key] || "").trim();
record[definition.key] = value;
}
return value ? { field: definition.key, value } : null;
}
function buildNewRecordTemplate(tableId) {
const columns = getTableColumns(tableId === "homeRequests" ? "requestTable" : tableId);
const hostedSample = tableSourceRows[tableId] && tableSourceRows[tableId].hostedRows.length
? tableSourceRows[tableId].hostedRows[0]
: null;
const fieldDefinitions = hostedSample
? Object.keys(hostedSample).filter((key) => !key.startsWith("__")).map((key) => ({ key }))
: columns;
const now = new Date();
const generatedIds = buildGeneratedRecordIds(tableId);
const record = {};
fieldDefinitions.forEach((column, index) => {
const key = column.key;
const normalizedKey = key.toLowerCase();
const sampleValue = hostedSample ? hostedSample[key] : "";
if (Object.prototype.hasOwnProperty.call(generatedIds, key)) {
record[key] = generatedIds[key];
} else if (["requestid", "caseid", "providerid", "customerreferenceno"].includes(normalizedKey)) {
record[key] = getFieldOptions(key, "")[0] || "";
} else if (/(^id$|id$|key$)/i.test(key)) {
record[key] = "";
} else if (/(?:at|timestamp)$/.test(normalizedKey)) {
record[key] = now.toISOString();
} else if (normalizedKey.includes("date") || normalizedKey.includes("checkin") || normalizedKey.includes("checkout")) {
record[key] = now.toISOString().slice(0, 10);
} else if (normalizedKey === "status") {
record[key] = "New";
} else if (normalizedKey === "priority" || normalizedKey === "severity") {
record[key] = "Medium";
} else if (normalizedKey === "owner" || normalizedKey === "manager" || normalizedKey.includes("primaryowner")) {
record[key] = activeProfile.displayName;
} else if (normalizedKey.includes("email")) {
record[key] = activeProfile.email;
} else if (normalizedKey === "region") {
record[key] = activeProfile.region;
} else if (normalizedKey === "organizationid") {
record[key] = getTenantId();
} else if (normalizedKey === "version") {
record[key] = 1;
} else if (/cost|price|fee|overhead|contingency|year\d|impact/.test(normalizedKey)) {
record[key] = "$0";
} else if (/capacity|beds|hours|guests|requests|placements|stays|fte/.test(normalizedKey)) {
record[key] = "0";
} else if (typeof sampleValue === "boolean") {
record[key] = false;
} else {
record[key] = "";
}
});
if (tableId === "requestTable" || tableId === "homeRequests") {
record.customerReferenceNo = generatedIds.customerReferenceNo;
record.caseId = "";
record.providerId = "";
record.requestedCheckIn = new Date(now.getTime() + (2 * 24 * 60 * 60 * 1000)).toISOString().slice(0, 10);
record.requestedCheckOut = new Date(now.getTime() + (9 * 24 * 60 * 60 * 1000)).toISOString().slice(0, 10);
} else if (Object.prototype.hasOwnProperty.call(record, "requestId")) {
const effectiveRequests = getEffectiveDatasourceRows("requests");
const linkedRequest = effectiveRequests.find((row) => row.caseId && row.providerId)
|| effectiveRequests[0];
const context = linkedRequest ? resolveLinkedContext("requestId", linkedRequest.id) : null;
if (context) {
Object.entries(context).forEach(([key, value]) => {
if (!(key in generatedIds) && !(tableId === "caseTable" && key === "caseId") && Object.prototype.hasOwnProperty.call(record, key)) {
record[key] = value;
}
});
}
}
return record;
}
function stripLocalMetadata(record) {
return Object.fromEntries(Object.entries(record).filter(([key]) => !key.startsWith("__")));
}
function renderRow(row, columns, tableId, index) {
return `
Edit
${columns.map((column) => `${column.formatter ? column.formatter(row[column.key], row) : escapeHtml(String(row[column.key] ?? ""))} `).join("")}
`;
}
function getTableSearchSuggestion(record, columns, namespace) {
const configuredIdentityKey = generatedIdDefinitions[namespace]?.key;
const identityColumn = columns.find((column) => /(^id$|id$|key$)/i.test(column.key)) || columns[0];
const identityKey = configuredIdentityKey && Object.prototype.hasOwnProperty.call(record, configuredIdentityKey)
? configuredIdentityKey
: identityColumn?.key;
const identity = String(record[identityKey] ?? "").trim();
const titleKeys = ["veteran", "name", "provider", "manager", "region", "type", "location", "city", "status"];
const title = titleKeys.map((key) => String(record[key] ?? "").trim()).find((value) => value && value !== identity) || identity || "Record";
const meta = [record.status, record.priority, record.phase, record.location || record.city || record.region]
.map((value) => String(value ?? "").trim())
.filter((value, index, values) => value && value !== title && values.indexOf(value) === index)
.slice(0, 3)
.join(" | ");
return {
value: identity || title,
label: identity && title !== identity ? `${identity} - ${title}` : title,
meta,
searchText: Object.values(record).filter((value) => typeof value !== "object").join(" ").toLowerCase()
};
}
function wireTableSearchTypeahead(input, getRows, columns, namespace) {
if (!input || input.dataset.tableTypeaheadBound === namespace) {
return;
}
const menu = input.parentElement?.querySelector(`[data-table-typeahead-menu='${namespace}']`);
if (!menu) {
return;
}
let activeIndex = -1;
let visibleSuggestions = [];
input.dataset.tableTypeaheadBound = namespace;
input.setAttribute("role", "combobox");
input.setAttribute("aria-autocomplete", "list");
input.setAttribute("aria-controls", menu.id);
input.setAttribute("aria-expanded", "false");
const closeMenu = () => {
menu.classList.remove("show");
input.setAttribute("aria-expanded", "false");
input.removeAttribute("aria-activedescendant");
activeIndex = -1;
};
const chooseSuggestion = (suggestion) => {
input.value = suggestion.value;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.focus();
closeMenu();
showToast("Search applied", `Showing records matching ${suggestion.value}.`, "info");
};
const setActiveOption = (nextIndex) => {
const options = Array.from(menu.querySelectorAll("[data-table-typeahead-option]"));
if (!options.length) {
activeIndex = -1;
return;
}
activeIndex = (nextIndex + options.length) % options.length;
options.forEach((option, index) => option.classList.toggle("active", index === activeIndex));
input.setAttribute("aria-activedescendant", options[activeIndex].id);
options[activeIndex].scrollIntoView({ block: "nearest" });
};
const renderSuggestions = () => {
const term = input.value.trim().toLowerCase();
const seen = new Set();
visibleSuggestions = getRows().map((record) => getTableSearchSuggestion(record, columns, namespace))
.filter((suggestion) => (!term || suggestion.searchText.includes(term)) && !seen.has(suggestion.value) && seen.add(suggestion.value))
.slice(0, 12);
menu.replaceChildren();
visibleSuggestions.forEach((suggestion, index) => {
const option = document.createElement("button");
option.className = "table-search-option";
option.type = "button";
option.id = `${namespace}-search-option-${index}`;
option.dataset.tableTypeaheadOption = namespace;
option.dataset.value = suggestion.value;
option.setAttribute("role", "option");
option.setAttribute("aria-selected", "false");
option.innerHTML = `${escapeHtml(suggestion.label)} ${suggestion.meta ? `${escapeHtml(suggestion.meta)} ` : ""}`;
option.addEventListener("mousedown", (event) => event.preventDefault());
option.addEventListener("click", () => chooseSuggestion(suggestion));
menu.append(option);
});
if (!visibleSuggestions.length) {
const empty = document.createElement("div");
empty.className = "table-search-empty";
empty.textContent = "No matching records";
menu.append(empty);
}
menu.classList.add("show");
input.setAttribute("aria-expanded", "true");
activeIndex = -1;
};
input.addEventListener("focus", renderSuggestions);
input.addEventListener("input", () => {
if (!input.value.trim()) {
closeMenu();
return;
}
renderSuggestions();
});
input.addEventListener("keydown", (event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!menu.classList.contains("show")) {
renderSuggestions();
}
setActiveOption(activeIndex + (event.key === "ArrowDown" ? 1 : -1));
} else if (event.key === "Enter" && activeIndex >= 0 && visibleSuggestions[activeIndex]) {
event.preventDefault();
chooseSuggestion(visibleSuggestions[activeIndex]);
} else if (event.key === "Escape") {
closeMenu();
}
});
input.addEventListener("blur", () => window.setTimeout(closeMenu, 120));
}
function bindTableInteractions(tableId, rows) {
const table = document.getElementById(tableId);
if (!table) {
return;
}
const columns = getTableColumns(tableId);
const source = tableSourceRows[tableId] || { hostedRows: cloneRows(rows), rows: resolveTableRows(tableId, rows, columns) };
const effectiveRows = source.rows;
const search = document.querySelector(`[data-table-search='${tableId}']`);
const filter = document.querySelector(`[data-table-filter='${tableId}']`);
const exportButton = document.querySelector(`[data-table-export='${tableId}']`);
const addButton = document.querySelector(`[data-table-add='${tableId}']`);
const resetButton = document.querySelector(`[data-table-reset='${tableId}']`);
const countChip = document.querySelector(`[data-table-count='${tableId}'] span:last-child`);
const registry = tableRegistry[tableId] || {};
const sortState = registry.sortState || { key: null, direction: "ascending" };
const externalFilter = registry.externalFilter || null;
const applyFilters = () => {
const currentRows = tableRegistry[tableId] ? tableRegistry[tableId].rows : effectiveRows;
const searchTerm = (search ? search.value : "").trim().toLowerCase();
const filterValue = filter ? filter.value : "";
const filterKey = table.dataset.filterKey;
const linkedFilter = tableRegistry[tableId] ? tableRegistry[tableId].externalFilter : externalFilter;
let visibleCount = 0;
Array.from(table.tBodies[0].rows).forEach((rowEl) => {
const rowData = currentRows[Number(rowEl.dataset.rowIndex)];
const rowText = Object.values(rowData).join(" ").toLowerCase();
const searchMatch = !searchTerm || rowText.includes(searchTerm);
const filterMatch = linkedFilter
? linkedFilter.values.includes(String(rowData[linkedFilter.key]))
: !filterValue || String(rowData[filterKey]) === filterValue;
rowEl.hidden = !(searchMatch && filterMatch);
if (!rowEl.hidden) {
visibleCount += 1;
}
});
if (countChip) {
countChip.textContent = `${visibleCount} of ${currentRows.length} records`;
}
};
const applySort = (sortKey, direction) => {
const currentRows = tableRegistry[tableId] ? tableRegistry[tableId].rows : effectiveRows;
currentRows.sort((left, right) => compareValues(left[sortKey], right[sortKey], direction));
currentRows.forEach((row, index) => {
row.__rowIndex = index;
});
table.tBodies[0].innerHTML = currentRows.map((row, index) => renderRow(row, columns, tableId, index)).join("");
bindTableInteractions(tableId, currentRows);
showToast("Sort applied", `${tableId} sorted by ${sortKey} ${direction}.`, "info");
};
if (search) {
if (search.dataset.boundTable !== tableId) {
search.addEventListener("input", () => {
if (tableRegistry[tableId]) {
tableRegistry[tableId].externalFilter = null;
}
applyFilters();
});
search.dataset.boundTable = tableId;
}
}
if (filter) {
if (filter.dataset.boundTable !== tableId) {
filter.addEventListener("change", () => {
if (tableRegistry[tableId]) {
tableRegistry[tableId].externalFilter = null;
}
applyFilters();
showToast("Filter applied", `Filtered ${tableId} by ${filter.value || "all items"}.`, "info");
});
filter.dataset.boundTable = tableId;
}
}
if (exportButton) {
if (exportButton.dataset.boundTable !== tableId) {
exportButton.addEventListener("click", () => {
if (!canPerform("export")) {
showToast("Permission required", `${activeProfile.role} cannot export this table.`, "danger");
recordActivity("table-export", "Table export blocked", `${tableId} was not exported because the active demo role lacks permission.`, "Blocked", { tableId });
return;
}
exportTableToCsv(tableId);
recordActivity("table-export", "Table exported", `${tableId} was exported as a CSV file.`, "Completed", { tableId });
showToast("CSV exported", `Downloaded ${tableId}.csv`, "success");
});
exportButton.dataset.boundTable = tableId;
}
}
if (addButton && addButton.dataset.boundTable !== tableId) {
addButton.addEventListener("click", async () => {
addButton.disabled = true;
try {
await openNewRecordEditor(tableId);
} finally {
addButton.disabled = false;
}
});
addButton.dataset.boundTable = tableId;
}
if (resetButton && resetButton.dataset.boundTable !== tableId) {
resetButton.addEventListener("click", () => resetLocalTable(tableId));
resetButton.dataset.boundTable = tableId;
}
tableRegistry[tableId] = { tableId, table, rows: effectiveRows, hostedRows: source.hostedRows, applyFilters, sortState, externalFilter };
wireTableSearchTypeahead(search, () => tableRegistry[tableId]?.rows || effectiveRows, columns, tableId);
table.querySelectorAll("[data-table-sort]").forEach((button) => {
const buttonKey = button.dataset.sortKey;
const currentSortState = tableRegistry[tableId].sortState;
const isActive = currentSortState.key === buttonKey;
const direction = isActive ? currentSortState.direction : "none";
button.setAttribute("aria-sort", direction);
button.querySelector(".sort-icon").className = getSortIconClass(direction);
if (button.dataset.boundTable !== tableId) {
button.addEventListener("click", () => {
const activeSortState = tableRegistry[tableId].sortState;
const nextDirection = activeSortState.key === buttonKey && activeSortState.direction === "ascending" ? "descending" : "ascending";
tableRegistry[tableId].sortState = { key: buttonKey, direction: nextDirection };
applySort(buttonKey, nextDirection);
});
button.dataset.boundTable = tableId;
}
});
if (table.dataset.boundRecords !== tableId) {
table.addEventListener("click", (event) => {
const button = event.target.closest("[data-table-record]");
if (!button) {
return;
}
const rowIndex = Number(button.dataset.rowIndex);
const rowData = tableRegistry[tableId].rows[rowIndex];
openRecordEditor(tableId, rowIndex, rowData);
});
table.dataset.boundRecords = tableId;
}
applyFilters();
}
function bindRecordButtons() {
document.querySelectorAll("[data-record]").forEach((button) => {
button.addEventListener("click", () => {
const details = getRecordDetails(button.dataset.record);
modalState = null;
openRecordModal(details.title, details.body, details.toast);
});
});
document.querySelectorAll("[data-row-action]").forEach((button) => {
if (button.dataset.boundAction === "true") {
return;
}
button.addEventListener("click", () => handleOperationalAction(button.dataset.rowAction, button));
button.dataset.boundAction = "true";
});
}
function canPerform(action) {
const rolePermissions = {
"Care Operations": ["route", "notify", "remote", "placement", "export"],
"Case Manager": ["route", "remote", "placement", "export"],
"Coordinated Entry Assessor": ["route", "remote", "placement", "export"],
"Consent Steward": ["remote", "export"],
"Inventory Coordinator": ["notify", "remote", "placement", "export"],
"Provider Success": ["notify", "remote", "placement", "export"],
"Program Analytics": ["export"],
"Government Programs": ["remote", "placement", "export"],
"System Administrator": ["route", "notify", "remote", "placement", "export"],
"Proposal Manager": ["export"]
};
return (rolePermissions[activeProfile?.role] || ["export"]).includes(action);
}
function getTenantId() {
const organization = String(activeProfile?.organization || "South Jersey Coordinated Care").trim();
const numericId = Array.from(organization.toUpperCase()).reduce((value, character) => ((value * 31) + character.charCodeAt(0)) % 999999, 0) + 1;
return `ORG-${String(numericId).padStart(6, "0")}`;
}
function getActivityHistory() {
return storageService.readProfile(activeProfile.profileId, "activity-history", []);
}
function recordActivity(type, title, details, status = "Local", references = {}) {
const activity = {
activityId: `ACT-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
profileId: activeProfile.profileId,
organization: activeProfile.organization,
tenantId: getTenantId(),
actor: activeProfile.displayName,
role: activeProfile.role,
purposeOfUse: activeProfile.purposeOfUse || "Care coordination",
sessionId: sessionAssurance?.sessionId || "",
type,
title,
details,
status,
references,
occurredAt: new Date().toISOString()
};
const history = getActivityHistory();
history.unshift(activity);
storageService.writeProfile(activeProfile.profileId, "activity-history", history.slice(0, 500));
storageService.putDurable(activeProfile.profileId, "activity", activity.activityId, activity).catch((error) => {
console.warn("Activity IndexedDB write failed", error);
});
return activity;
}
async function submitRemoteOperation(operationType, payload, activityTitle, operationContext = {}) {
const purposeOfUse = `Role-scoped access: ${activeProfile?.role || "Unassigned"}`;
if (!canPerform("remote")) {
showToast("Permission required", `${activeProfile.role} cannot submit this shared operation in the demo role model.`, "danger");
recordActivity(operationType, activityTitle, "Remote submission blocked by the demo role policy.", "Blocked");
return { ok: false, blocked: true, status: 0, response: null, error: "Remote submission blocked by the demo role policy.", submittedAt: new Date().toISOString() };
}
if (!apiService) {
showToast("Remote service unavailable", "The remote submission service did not load. The local operation is still saved.", "warning");
recordActivity(operationType, activityTitle, "Remote service was unavailable; local state was retained.", "Failed");
return { ok: false, status: 0, response: null, error: "Remote submission service unavailable.", submittedAt: new Date().toISOString() };
}
const credentialType = /update|retry|upsert|inventory|placement|match|approve|monitor/i.test(operationType) ? "update" : "create";
if (!apiService.hasCredential?.(credentialType)) {
showToast("Remote API credential required", `Open Profile > Synchronization and configure the session-only ${credentialType} API key before using Save and submit.`, "danger");
recordActivity(operationType, activityTitle, "Remote submission blocked because the profile session had no API credential.", "Blocked");
return { ok: false, blocked: true, credentialRequired: true, status: 0, response: null, error: "Remote API credential is required in the profile session.", submittedAt: new Date().toISOString() };
}
showToast("Submitting operation", "Sending the JSON payload to the shared endpoint.", "primary");
try {
const result = await apiService.submitOperation(operationType, payload, {
...activeProfile,
operationId: operationContext.operationId,
correlationId: operationContext.correlationId,
idempotencyKey: operationContext.idempotencyKey,
organizationId: getTenantId(),
purposeOfUse,
dataClassification: "Sensitive care coordination demonstration data",
minimumNecessary: true,
consentChecked: hasConsentEvidence(payload),
expectedVersion: payload?.expectedPreviousVersion ?? payload?.recordVersion ?? null
});
recordActivity(operationType, activityTitle, `Remote endpoint accepted the operation with status ${result.status}.`, "Submitted", {
submittedAt: result.submittedAt,
operationId: result.operationId,
correlationId: result.correlationId,
idempotencyKey: result.idempotencyKey,
rowKey: result.rowKey || ""
});
await storageService.putDurable(activeProfile.profileId, "remote-receipts", result.operationId, {
operationId: result.operationId,
operationType,
correlationId: result.correlationId,
idempotencyKey: result.idempotencyKey,
rowKey: result.rowKey || "",
status: result.status,
recordReference: payload?.primaryKey?.value || payload?.recordIdentity || payload?.placementId || payload?.caseId || payload?.requestId || "",
response: result.response,
tenantId: getTenantId(),
purposeOfUse,
submittedAt: result.submittedAt
}).catch((error) => console.warn("Remote receipt IndexedDB save failed", error));
showToast("Remote submission accepted", "The operation was saved locally and accepted by the shared endpoint.", "success");
return result;
} catch (error) {
console.warn("Remote operation submission failed", error);
recordActivity(operationType, activityTitle, error.message, "Failed");
const queuedAt = operationContext.queuedAt || new Date().toISOString();
const queueId = operationContext.queueId || `QUEUE-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const attemptCount = Number(operationContext.attemptCount || 0) + 1;
const retryDelayMinutes = Math.min(60, 2 ** Math.min(attemptCount, 5));
await storageService.putDurable(activeProfile.profileId, "remote-queue", queueId, {
queueId,
operationId: error.operationId || operationContext.operationId || `OP-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
correlationId: error.correlationId || operationContext.correlationId || "",
idempotencyKey: error.idempotencyKey || operationContext.idempotencyKey || "",
operationType,
payload,
tenantId: getTenantId(),
purposeOfUse,
status: "Retry required",
attemptCount,
lastError: error.message,
nextRetryAt: new Date(Date.now() + (retryDelayMinutes * 60 * 1000)).toISOString(),
queuedAt,
updatedAt: queuedAt
}).catch((queueError) => console.warn("Remote retry queue save failed", queueError));
showToast("Remote submission failed", `${error.message} The local operation remains available for retry.`, "danger");
return {
ok: false,
status: error.status || 0,
response: error.response ?? null,
error: error.message,
submittedAt: new Date().toISOString()
};
}
}
function validateRemoteProfileConfiguration(type = "create") {
if (apiService?.hasCredential?.(type)) return true;
showToast("Remote API credential required", `Open Profile > Synchronization and configure the session-only ${type} API key before continuing.`, "danger");
return false;
}
function hasConsentEvidence(payload) {
const values = [];
const visit = (value, depth = 0) => {
if (depth > 6 || value === null || value === undefined) return;
if (Array.isArray(value)) {
value.forEach((item) => visit(item, depth + 1));
return;
}
if (typeof value !== "object") return;
Object.entries(value).forEach(([key, item]) => {
if (/consent(status)?/i.test(key) && typeof item !== "object") values.push(String(item).toLowerCase());
visit(item, depth + 1);
});
};
visit(payload);
return values.some((value) => ["active", "granted", "verified", "yes", "true"].includes(value));
}
function persistRecordPatch(tableId, record, index, patch) {
const state = readLocalTableState(tableId);
const savedAt = new Date().toISOString();
const update = { ...patch, updatedAt: savedAt, __localUpdatedAt: savedAt };
if (record.__localRecordId) {
const localIndex = state.addedRecords.findIndex((candidate) => candidate.__localRecordId === record.__localRecordId);
if (localIndex >= 0) {
state.addedRecords[localIndex] = { ...state.addedRecords[localIndex], ...update };
}
} else {
const identity = getRecordIdentity(record, getTableColumns(tableId), index);
state.updates[identity] = { ...(state.updates[identity] || {}), ...stripLocalMetadata(update) };
}
writeLocalTableState(tableId, state);
}
async function handleOperationalAction(action, button) {
button.disabled = true;
try {
if (action === "assign") {
if (!canPerform("route")) {
showToast("Permission required", `${activeProfile.role} cannot route requests.`, "danger");
return;
}
const requests = getEffectiveDatasourceRows("requests");
const candidates = requests
.map((record, index) => ({ record, index }))
.filter(({ record }) => record.priority === "Critical" && !["Completed", "Checked In"].includes(record.status));
const assignedAt = new Date();
candidates.forEach(({ record, index }) => persistRecordPatch("requestTable", record, index, {
status: record.status === "Submitted" ? "Under Review" : record.status,
assignedOwner: activeProfile.displayName,
assignedProfileId: activeProfile.profileId,
assignedAt: assignedAt.toISOString(),
slaDueAt: new Date(assignedAt.getTime() + (4 * 60 * 60 * 1000)).toISOString()
}));
refreshConnectedTableState("requestTable");
recordActivity("critical-auto-route", "Critical requests routed", `${candidates.length} requests were assigned with a four-hour review SLA.`, "Local", { count: candidates.length });
showToast("Critical routing complete", `${candidates.length} requests were assigned to ${activeProfile.displayName}.`, "success");
await submitRemoteOperation("critical-auto-route", {
count: candidates.length,
requestIds: candidates.map(({ record }) => record.id),
owner: activeProfile.displayName,
assignedAt: assignedAt.toISOString()
}, "Critical routing shared");
return;
}
if (action === "notify") {
if (!canPerform("notify")) {
showToast("Permission required", `${activeProfile.role} cannot notify provider partners.`, "danger");
return;
}
const providers = getEffectiveDatasourceRows("providers")
.filter((record) => record.status === "Waitlist" || Number(record.availableUnits || 0) > 0)
.slice(0, 100);
recordActivity("provider-waitlist-notification", "Provider availability request prepared", `${providers.length} provider contacts were prepared for notification.`, "Local", { count: providers.length });
await submitRemoteOperation("provider-waitlist-notification", {
providerIds: providers.map((record) => record.providerId),
contacts: providers.map((record) => ({ providerId: record.providerId, contactEmail: record.contactEmail })),
requestedResponseBy: new Date(Date.now() + (2 * 60 * 60 * 1000)).toISOString()
}, "Provider availability request submitted");
return;
}
if (action === "export") {
if (!canPerform("export")) {
showToast("Permission required", `${activeProfile.role} cannot export reports.`, "danger");
return;
}
exportTableToCsv("reportTable");
recordActivity("report-export", "Monthly snapshot exported", "The currently filtered reporting table was downloaded as CSV.", "Completed");
showToast("Snapshot exported", "The visible monthly reporting rows were downloaded as CSV.", "success");
}
} finally {
button.disabled = false;
}
}
function handleGlobalSearch() {
const term = searchInput.value.trim().toLowerCase();
document.querySelectorAll(".section-card, .hero-panel, .metric-card, .story-card, .timeline-card, .insight-card, .cta-strip, .flow-card").forEach((block) => {
const text = block.textContent.toLowerCase();
block.style.outline = term && text.includes(term) ? "2px solid rgba(37, 99, 235, 0.35)" : "";
});
}
function buildUxJourneyPayload(activeForm) {
const allStepForms = Array.from(document.querySelectorAll("[data-ux-intake-form]"));
const allSteps = allStepForms.map((stepForm, index) => {
const formData = new FormData(stepForm);
const fields = Object.fromEntries(formData.entries());
const completedFieldCount = Object.values(fields).filter((value) => String(value).trim() !== "").length;
return {
stepNumber: index + 1,
stepId: stepForm.dataset.uxIntakeForm,
stepTitle: stepForm.dataset.uxIntakeTitle,
isSubmittedStep: stepForm === activeForm,
isComplete: completedFieldCount > 0,
completedFieldCount,
fields
};
});
const submittedStepFields = allSteps.find((step) => step.isSubmittedStep)?.fields || {};
return {
flowId: `UX-LOCAL-${Date.now()}`,
profileId: activeProfile.profileId,
customerReferenceNo: submittedStepFields.customerReferenceNo || "",
requestId: submittedStepFields.requestId || "",
caseId: submittedStepFields.caseId || "",
providerId: submittedStepFields.providerId || "",
stepId: activeForm.dataset.uxIntakeForm,
stepTitle: activeForm.dataset.uxIntakeTitle,
sentAt: new Date().toISOString(),
sampleSource: "BeaReponseCare UX flow sample",
totalSteps: allSteps.length,
completedSteps: allSteps.filter((step) => step.isComplete).length,
submittedStepFields,
journeySteps: allSteps
};
}
async function openRecordEditor(tableId, rowIndex, rowData) {
try {
await Promise.all(Object.keys(dataUrls).map((key) => fetchDataset(key)));
} catch (error) {
console.warn("Connected datasource preload failed", error);
showToast("Connected data limited", "The primary record is available, but some related tabs could not be loaded.", "warning");
}
const columns = getTableColumns(tableId);
modalState = {
mode: "table-edit",
tableId,
rowIndex,
recordIdentity: getRecordIdentity(rowData, columns, rowIndex),
isLocalRecord: Boolean(rowData.__localRecordId),
expectedVersion: Number(rowData.version || 1),
openedUpdatedAt: rowData.updatedAt || ""
};
const record = stripLocalMetadata(rowData);
openRecordModal("Edit connected record", renderRecordWorkspace(tableId, rowData), "Record updated");
}
async function openNewRecordEditor(tableId) {
if (generatedIdDefinitions[tableId]) {
showToast("Refreshing record IDs", "Checking hosted and profile-local records before generating a unique ID.", "primary");
try {
await refreshBeforeIdGeneration(tableId);
} catch (error) {
console.error(`${tableId} ID refresh failed`, error);
showToast("Refresh required", "The latest records could not be confirmed, so a new ID was not generated.", "danger");
return;
}
}
const record = buildNewRecordTemplate(tableId);
const identityDefinition = generatedIdDefinitions[tableId];
modalState = {
mode: "table-create",
tableId
};
if (tableId === "requestTable" || tableId === "homeRequests") {
openRecordModal("New veteran intake", createVeteranIntakeMarkup(record), "Veteran intake created");
bindVeteranIntakeWizard();
return;
}
openRecordModal("New local record", createEditableRecordMarkup(record, {
tableId,
readOnlyKeys: identityDefinition ? [identityDefinition.key] : []
}), "Record created");
}
function createVeteranIntakeMarkup(record) {
return `
Step 1 of 5
Veteran profile
Save intake draft locally
Resume draft
Load sample data
Demonstration workspace: use sample or non-sensitive documents only. Uploaded files remain in this browser's Cache API and are not sent remotely with the intake. Production use requires authenticated roles, encryption, malware scanning, retention controls, and audited access.
Veteran profile
${escapeHtml(record.id)} Generated request ID | Customer reference ${escapeHtml(record.customerReferenceNo)}
Veteran name
Branch of service
Select branch
${["Army", "Navy", "Air Force", "Marine Corps", "Coast Guard", "Space Force"].map((value) => `${value} `).join("")}
Referral source
Select source
${["VA social worker", "Community clinic", "Hospital discharge team", "Self-referral", "Veteran service organization"].map((value) => `${value} `).join("")}
Referral office
Intake mode
Assisted intake
Self-service
Entered by
Preferred contact
${["Phone", "SMS", "Email", "Secure message"].map((value) => `${value} `).join("")}
Mailing address
Daytime phone
Evening phone
Cell phone
Email address
Best contact time Daytime Evening Any time
Urgency and accommodation needs
Priority
${["Critical", "High", "Medium", "Low"].map((value) => `${value} `).join("")}
Accessibility needs
Select need
${["None reported", "Wheelchair access", "Service animal support", "Ground-floor room"].map((value) => `${value} `).join("")}
Transportation needed
No
Yes
Situation and placement notes
${escapeHtml(record.caseNote)}
Mobility needs
Sensory or communication needs
Safety constraints
Consent method
Verbal Written Electronic
Consent status
Granted Pending Declined
Supporting document
Pending Stored locally Verified Not required
Document type
Referral Eligibility evidence Discharge plan Other metadata only
Document reference
Document label
Associated with request ${escapeHtml(record.id)}
Store document locally
No documents are stored for this request.
Income and authorized representative
Enter monthly amounts. Use zero when a listed source does not apply.
Review and submit
Confirm the intake details below. Submitting saves the JSON record to this browser profile and IndexedDB, then places it at the top of the request table.
${["id", "customerReferenceNo", "caseId", "providerId", "createdAt", "updatedAt"].map((key) => ` `).join("")}
Back
Browser-local draft and durable IndexedDB backup
`;
}
function bindVeteranIntakeWizard() {
const form = recordModalBody.querySelector("[data-veteran-intake-form]");
if (!form) {
return;
}
const steps = Array.from(form.querySelectorAll("[data-intake-step]"));
const stepTitles = ["Veteran profile", "Stay request", "Needs and urgency", "Income and representative", "Certification and submit"];
const progress = form.querySelector("[data-intake-progress]");
const progressContainer = progress.closest("[role='progressbar']");
const stepLabel = form.querySelector("[data-intake-step-label]");
const stepTitle = form.querySelector("[data-intake-step-title]");
const backButton = form.querySelector("[data-intake-back]");
const requestId = form.elements.namedItem("id").value;
const documentLabelInput = form.elements.namedItem("documentLabel");
const documentFileInput = form.querySelector("#intake-document-file");
const documentList = form.querySelector("[data-intake-document-list]");
const documentStoreButton = form.querySelector("[data-intake-document-store]");
let cachedDocuments = [];
let activeStep = 0;
const renderCachedDocuments = async () => {
cachedDocuments = await storageService.listCachedDocuments(activeProfile.profileId, requestId).catch((error) => {
console.warn("Cached document listing failed", error);
return [];
});
form.elements.namedItem("documentCount").value = String(cachedDocuments.length);
form.elements.namedItem("cachedDocumentIds").value = JSON.stringify(cachedDocuments.map((document) => document.documentId));
if (!documentList) return;
documentList.innerHTML = cachedDocuments.length ? `${cachedDocuments.map((document) => `
${escapeHtml(document.label)} ${escapeHtml(document.fileName)} · ${escapeHtml(formatBytes(document.size))} · ${escapeHtml(document.documentId)}
Open
Remove
`).join("")}
` : 'No documents are stored for this request.
';
};
documentStoreButton?.addEventListener("click", async () => {
const label = documentLabelInput.value.trim();
const file = documentFileInput.files?.[0];
if (!label || !file) {
showToast("Document details required", "Add a document label and choose a file before storing it.", "danger");
return;
}
if (file.size > 10 * 1024 * 1024) {
showToast("Document too large", "Choose a document that is 10 MB or smaller.", "danger");
return;
}
documentStoreButton.disabled = true;
try {
const metadata = await storageService.putCachedDocument(activeProfile.profileId, requestId, label, file, form.elements.namedItem("documentType").value);
form.elements.namedItem("documentName").value = metadata.fileName;
form.elements.namedItem("documentStatus").value = "Stored locally";
documentLabelInput.value = "";
documentFileInput.value = "";
await renderCachedDocuments();
updateReview();
showToast("Document stored locally", `${metadata.label} is associated with ${requestId} in this browser cache.`, "success");
} catch (error) {
console.error("Document cache save failed", error);
showToast("Document not stored", "The browser Cache API could not preserve this document. Check storage permissions and try again.", "danger");
} finally {
documentStoreButton.disabled = false;
}
});
documentList?.addEventListener("click", async (event) => {
const openButton = event.target.closest("[data-intake-document-open]");
const deleteButton = event.target.closest("[data-intake-document-delete]");
if (openButton) {
const cached = await storageService.getCachedDocument(activeProfile.profileId, requestId, openButton.dataset.intakeDocumentOpen);
if (!cached) {
showToast("Document unavailable", "The cached file could not be found in this browser.", "danger");
return;
}
const blobUrl = URL.createObjectURL(await cached.response.blob());
window.open(blobUrl, "_blank", "noopener,noreferrer");
window.setTimeout(() => URL.revokeObjectURL(blobUrl), 60000);
}
if (deleteButton) {
await storageService.deleteCachedDocument(activeProfile.profileId, requestId, deleteButton.dataset.intakeDocumentDelete);
await renderCachedDocuments();
updateReview();
showToast("Document removed", `The cached document was removed from ${requestId}.`, "success");
}
});
const serializeDraft = () => ({
...Object.fromEntries(new FormData(form).entries()),
draftStep: activeStep,
savedAt: new Date().toISOString()
});
const applyPayload = (payload) => {
Object.entries(payload || {}).forEach(([name, value]) => {
const control = form.elements.namedItem(name);
if (control && typeof value !== "object") {
if (control.type === "checkbox") {
control.checked = value === control.value || value === true || value === "true";
} else {
control.value = String(value ?? "");
}
control._syncTypeahead?.();
}
});
};
const calculateTriage = () => {
const values = Object.fromEntries(new FormData(form).entries());
const reasons = [];
let score = 0;
const checkInTime = new Date(`${values.requestedCheckIn || "2999-12-31"}T12:00:00`).getTime();
const daysUntilCheckIn = Math.ceil((checkInTime - Date.now()) / (24 * 60 * 60 * 1000));
if (daysUntilCheckIn <= 1) {
score += 3;
reasons.push("check-in is due within 24 hours");
} else if (daysUntilCheckIn <= 3) {
score += 2;
reasons.push("check-in is due within three days");
}
if (values.safetyConstraints?.trim()) {
score += 3;
reasons.push("safety constraints require review");
}
if (values.accessibilityNeeds && values.accessibilityNeeds !== "None reported") {
score += 1;
reasons.push("an accessibility match is required");
}
if (values.transportationNeeded === "true") {
score += 1;
reasons.push("transportation coordination is needed");
}
if (Number(values.dependents || 0) > 0 || values.serviceAnimal === "Yes") {
score += 1;
reasons.push("household placement constraints apply");
}
const recommendation = score >= 6 ? "Critical" : score >= 4 ? "High" : score >= 2 ? "Medium" : "Low";
const explanation = reasons.length ? reasons.join("; ") : "no urgent constraints are currently recorded";
form.elements.namedItem("triageRecommendation").value = recommendation;
form.elements.namedItem("triageReasons").value = explanation;
const panel = form.querySelector("[data-triage-recommendation]");
if (panel) {
panel.innerHTML = `Triage recommendation ${escapeHtml(recommendation)} priority
Because ${escapeHtml(explanation)}. A case manager may override this recommendation below.
`;
}
return { recommendation, explanation };
};
const updateReview = () => {
const formData = new FormData(form);
const reviewFields = [
["Request ID", formData.get("id")],
["Customer Reference", formData.get("customerReferenceNo")],
["Veteran", formData.get("veteran")],
["Service", formData.get("branchOfService")],
["Stay", formData.get("type")],
["Location", formData.get("location")],
["Dates", `${formData.get("requestedCheckIn") || "Not set"} to ${formData.get("requestedCheckOut") || "Not set"}`],
["Recommended priority", formData.get("triageRecommendation") || calculateTriage().recommendation],
["Consent", `${formData.get("consentStatus") || "Not set"} via ${formData.get("consentMethod") || "Not set"}`],
["Monthly income", formatCurrency(["monthlyVaCompensation", "monthlySocialSecurity", "monthlyEmploymentIncome", "monthlyPensionIncome", "monthlyOtherIncome"].reduce((total, key) => total + Number(formData.get(key) || 0), 0))],
["Documents", `${formData.get("documentCount") || "0"} cached locally · ${formData.get("documentStatus") || "Not set"}: ${formData.get("documentName") || formData.get("documentType") || "No reference"}`]
];
form.querySelector("[data-intake-review]").innerHTML = reviewFields.map(([label, value]) => `
${escapeHtml(label)}
${escapeHtml(String(value || "Not provided"))}
`).join("");
};
const showStep = (nextStep) => {
activeStep = Math.max(0, Math.min(nextStep, steps.length - 1));
steps.forEach((step, index) => step.classList.toggle("d-none", index !== activeStep));
const percent = Math.round(((activeStep + 1) / steps.length) * 100);
progress.style.width = `${percent}%`;
progress.textContent = `${percent}%`;
progressContainer.setAttribute("aria-valuenow", String(percent));
stepLabel.textContent = `Step ${activeStep + 1} of ${steps.length}`;
stepTitle.textContent = stepTitles[activeStep];
backButton.disabled = activeStep === 0;
modalPrimaryAction.textContent = activeStep === steps.length - 1 ? "Save intake locally" : "Continue to next step";
modalRemoteAction?.classList.toggle("d-none", activeStep !== steps.length - 1);
if (modalRemoteAction) modalRemoteAction.textContent = "Save intake & submit";
if (activeStep === steps.length - 1) {
calculateTriage();
updateReview();
}
};
const validateStep = () => {
const currentStep = steps[activeStep];
const checkIn = form.elements.namedItem("requestedCheckIn");
const checkOut = form.elements.namedItem("requestedCheckOut");
checkOut.setCustomValidity(checkIn.value && checkOut.value && checkOut.value < checkIn.value ? "Check-out must be on or after check-in." : "");
const representativeName = form.elements.namedItem("legalRepresentativeName");
const representativePhone = form.elements.namedItem("legalRepresentativePhone");
const representativeRequired = form.elements.namedItem("hasLegalRepresentative")?.value === "Yes";
representativeName.required = representativeRequired;
representativePhone.required = representativeRequired;
const otherIncomeSource = form.elements.namedItem("otherIncomeSource");
otherIncomeSource.required = Number(form.elements.namedItem("monthlyOtherIncome")?.value || 0) > 0;
const invalidControl = Array.from(currentStep.querySelectorAll("input, select, textarea")).find((control) => !control.checkValidity());
if (invalidControl) {
invalidControl.reportValidity();
showToast("Complete this step", "Provide the required intake details before continuing.", "danger");
return false;
}
return true;
};
form.querySelector("[data-veteran-sample]").addEventListener("click", () => {
const checkIn = new Date(Date.now() + (2 * 24 * 60 * 60 * 1000));
const checkOut = new Date(Date.now() + (9 * 24 * 60 * 60 * 1000));
const sample = {
veteran: "Daniel Brooks",
branchOfService: "Army",
referralSource: "VA social worker",
referralOffice: "Camden County Office of Veterans Affairs",
intakeMode: "Assisted intake",
enteredBy: activeProfile?.displayName || activeProfile?.name || "Demo case manager",
preferredContactMethod: "Phone",
streetAddress: "214 Market Street, Camden, NJ 08102",
vaFileNumberLast4: "4826",
daytimePhone: "(856) 555-0142",
eveningPhone: "(856) 555-0168",
cellPhone: "(856) 555-0191",
emailAddress: "daniel.brooks@example.org",
bestContactTime: "Daytime",
type: "Medical Travel",
location: "Camden, NJ",
guests: "1",
dependents: "0",
serviceAnimal: "No",
travelRadiusMiles: "25",
requestedCheckIn: checkIn.toISOString().slice(0, 10),
requestedCheckOut: checkOut.toISOString().slice(0, 10),
priority: "High",
accessibilityNeeds: "Ground-floor room",
transportationNeeded: "true",
mobilityNeeds: "Ground-floor access; no transfer assistance required",
sensoryNeeds: "None reported",
safetyConstraints: "",
consentMethod: "Verbal",
consentStatus: "Granted",
documentStatus: "Verified",
documentType: "Referral",
documentName: "VA-REF-DEMO-2026-09",
monthlyVaCompensation: "2450.00",
monthlySocialSecurity: "0",
monthlyEmploymentIncome: "850.00",
monthlyPensionIncome: "0",
monthlyOtherIncome: "0",
otherIncomeSource: "",
hasLegalRepresentative: "No",
legalRepresentativeName: "",
legalRepresentativePhone: "",
certificationName: "Daniel Brooks",
certificationDate: new Date().toISOString().slice(0, 10),
certificationAttestation: "Certified",
caseNote: "Veteran needs short-term lodging near a scheduled VA specialty appointment and requires transportation coordination.",
status: "Submitted"
};
Object.entries(sample).forEach(([name, value]) => {
const control = form.elements.namedItem(name);
if (control) {
if (control.type === "checkbox") {
control.checked = value === control.value;
} else {
control.value = value;
}
control._syncTypeahead?.();
}
});
calculateTriage();
updateReview();
showToast("Sample loaded", "A realistic veteran intake example is ready for review and editing.", "success");
});
form.querySelector("[data-veteran-save-draft]")?.addEventListener("click", async () => {
const payload = serializeDraft();
storageService.writeProfile(activeProfile.profileId, "intake-draft:request", payload);
await storageService.putDurable(activeProfile.profileId, "intake-draft", "request", payload).catch((error) => {
console.warn("IndexedDB intake draft save failed", error);
});
showToast("Draft saved", "This intake can be resumed from the current browser profile.", "success");
});
form.querySelector("[data-veteran-resume-draft]")?.addEventListener("click", async () => {
let payload = storageService.readProfile(activeProfile.profileId, "intake-draft:request", null);
if (!payload) {
payload = await storageService.getDurable(activeProfile.profileId, "intake-draft", "request", null).catch(() => null);
}
if (!payload) {
showToast("No saved draft", "Save an intake draft for this profile before attempting to resume it.", "info");
return;
}
applyPayload(payload);
calculateTriage();
showStep(Number(payload.draftStep || 0));
showToast("Draft resumed", "The most recently saved browser-local intake draft is ready.", "success");
});
backButton.addEventListener("click", () => showStep(activeStep - 1));
form.addEventListener("input", () => {
calculateTriage();
updateReview();
});
form.addEventListener("submit", (event) => event.preventDefault());
const handleIntakeAction = async (submitRemote = false) => {
if (!validateStep()) {
return;
}
if (activeStep < steps.length - 1) {
showStep(activeStep + 1);
return;
}
const triage = calculateTriage();
form.elements.namedItem("priority").value = form.elements.namedItem("priorityOverride").value || triage.recommendation;
await renderCachedDocuments();
const documentMetadata = {
requestId: form.elements.namedItem("id").value,
documentType: form.elements.namedItem("documentType").value,
documentName: form.elements.namedItem("documentName").value,
documentStatus: form.elements.namedItem("documentStatus").value,
documentCount: cachedDocuments.length,
attachments: cachedDocuments,
recordedAt: new Date().toISOString()
};
await storageService.putDurable(activeProfile.profileId, "document-metadata", documentMetadata.requestId, documentMetadata).catch((error) => {
console.warn("Document metadata save failed", error);
});
storageService.removeProfile(activeProfile.profileId, "intake-draft:request");
storageService.deleteDurable(activeProfile.profileId, "intake-draft", "request").catch(() => false);
await saveModalEdits({ submitRemote });
};
modalPrimaryAction.onclick = () => handleIntakeAction(false);
if (modalRemoteAction) modalRemoteAction.onclick = () => handleIntakeAction(true);
calculateTriage();
renderCachedDocuments();
showStep(0);
}
function openRecordModal(title, body, toastMessage) {
if (!recordModalLabel || !recordModalBody || !modalPrimaryAction) {
return;
}
recordModalLabel.textContent = title;
recordModalBody.innerHTML = body;
modalRemoteAction?.classList.add("d-none");
if (modalRemoteAction) modalRemoteAction.onclick = null;
const modalDialog = recordModal.querySelector(".modal-dialog");
const hasRecordWorkspace = Boolean(recordModalBody.querySelector("[data-record-workspace]"));
modalDialog?.classList.toggle("modal-xl", hasRecordWorkspace);
modalDialog?.classList.toggle("modal-lg", !hasRecordWorkspace);
wireModalTypeaheadDropdowns(recordModalBody);
recordModalBody.querySelectorAll("[data-editable-record-form]").forEach(bindRecordValidationReset);
bindLinkedDatasourceFields(recordModalBody);
bindSampleDataActions(recordModalBody);
bindConnectedRecordForms(recordModalBody);
bindConnectedTableWorkspaces(recordModalBody);
bindModalRecordTabActions();
bindNavigationButtons();
if (modalState && (modalState.mode === "table-edit" || modalState.mode === "table-create")) {
modalPrimaryAction.textContent = "Save primary record locally";
modalPrimaryAction.onclick = () => {
saveModalEdits({ submitRemote: false });
};
modalRemoteAction?.classList.remove("d-none");
if (modalRemoteAction) modalRemoteAction.textContent = "Save primary record & submit";
if (modalRemoteAction) modalRemoteAction.onclick = () => saveModalEdits({ submitRemote: true });
} else {
const standaloneForm = recordModalBody.querySelector("[data-editable-record-form]");
modalPrimaryAction.textContent = standaloneForm ? "Save form locally" : "Save changes";
modalPrimaryAction.onclick = standaloneForm
? () => saveStandaloneModalFormLocally(standaloneForm, title)
: () => showToast("Action completed", toastMessage, "success");
}
updateModalFooterForActiveRecordTab();
if (modalInstance) {
modalInstance.show();
}
}
async function saveStandaloneModalFormLocally(form, title) {
if (!activeProfile || !form) return;
clearStaleRecordValidation(form);
if (!form.reportValidity()) {
showToast("Validation required", "Complete the form fields before saving locally.", "danger");
return;
}
const savedAt = new Date().toISOString();
const snapshotId = `FORM-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const snapshot = {
snapshotId,
title,
profileId: activeProfile.profileId,
organizationId: getTenantId(),
formData: Object.fromEntries(new FormData(form).entries()),
syncStatus: "Local only",
savedAt
};
try {
storageService.writeProfile(activeProfile.profileId, `form-snapshot:${snapshotId}`, snapshot);
await storageService.putDurable(activeProfile.profileId, "form-snapshots", snapshotId, snapshot);
recordActivity("form-local-save", "Form saved locally", `${title} was saved to the active browser profile.`, "Local", { snapshotId });
showToast("Form saved locally", `${title} is stored in this browser profile and IndexedDB.`, "success");
} catch (error) {
console.error("Standalone form local save failed", error);
showToast("Local save failed", "The form could not be saved in this browser. Check storage permissions and try again.", "danger");
}
}
async function saveModalEdits(options = {}) {
if (!modalState || (modalState.mode !== "table-edit" && modalState.mode !== "table-create")) {
return;
}
if (options.submitRemote && !validateRemoteProfileConfiguration(modalState.mode === "table-edit" ? "update" : "create")) {
return;
}
const form = recordModalBody.querySelector("[data-editable-record-form]");
if (!form) {
return;
}
clearStaleRecordValidation(form);
if (!form.reportValidity()) {
showToast("Validation required", "Complete the modal fields before saving.", "danger");
return;
}
const registry = tableRegistry[modalState.tableId];
if (!registry) {
showToast("Save failed", "The table state is no longer available for this record.", "danger");
return;
}
const isCreate = modalState.mode === "table-create";
showToast(isCreate ? "Intake started" : "Save started", isCreate ? "Adding a profile-local record." : "Updating the selected record for this profile.", "primary");
const formData = new FormData(form);
const updatedEntries = Object.fromEntries(formData.entries());
const existingRecord = modalState.mode === "table-edit" ? tableRegistry[modalState.tableId]?.rows?.[modalState.rowIndex] || {} : {};
if (!applyRecordValidation(form, modalState.tableId, { ...existingRecord, ...updatedEntries })) {
form.reportValidity();
return;
}
const savedAt = new Date().toISOString();
let savedRecord = null;
let savedIdentity = "";
try {
const state = readLocalTableState(registry.tableId);
if (isCreate) {
const newRecord = {
...updatedEntries,
sourceSystem: "Profile-local workspace",
verificationStatus: updatedEntries.verificationStatus || "Pending verification",
syncStatus: options.submitRemote ? "Queued" : "Local only",
effectiveAt: updatedEntries.effectiveAt || savedAt,
organizationId: updatedEntries.organizationId || getTenantId(),
version: 1,
updatedBy: activeProfile.profileId,
createdAt: updatedEntries.createdAt || savedAt,
updatedAt: savedAt,
__localRecordId: `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
__createdByProfileId: activeProfile.profileId,
__localUpdatedAt: savedAt
};
getRecordPrimaryKey(registry.tableId, newRecord);
const identityDefinition = generatedIdDefinitions[registry.tableId];
if (identityDefinition) {
const latestRows = getRowsForIdGeneration(registry.tableId);
const proposedId = String(newRecord[identityDefinition.key] || "");
if (latestRows.some((record) => String(record[identityDefinition.key] || "") === proposedId)) {
const replacementId = generateNextRecordId(latestRows, identityDefinition);
newRecord[identityDefinition.key] = replacementId;
showToast("Unique ID regenerated", `${proposedId} was already in use. ${replacementId} was assigned instead.`, "warning");
}
}
state.addedRecords.unshift(newRecord);
writeLocalTableState(registry.tableId, state);
savedRecord = newRecord;
savedIdentity = getRecordIdentity(newRecord, getTableColumns(registry.tableId), 0);
} else {
const targetRecord = registry.rows[modalState.rowIndex];
if (versionedTableIds.has(registry.tableId)) {
const persistedRecord = modalState.isLocalRecord
? state.addedRecords.find((record) => record.__localRecordId === targetRecord.__localRecordId)
: state.updates[modalState.recordIdentity];
const currentVersion = Number(persistedRecord?.version || targetRecord.version || 1);
if (currentVersion !== Number(modalState.expectedVersion || 1)) {
const conflictId = `CONFLICT-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
await storageService.putDurable(activeProfile.profileId, "conflict-drafts", conflictId, {
conflictId,
tableId: registry.tableId,
recordIdentity: modalState.recordIdentity,
expectedVersion: modalState.expectedVersion,
currentVersion,
attemptedEdits: updatedEntries,
currentRecord: stripLocalMetadata(targetRecord),
savedAt: new Date().toISOString()
}).catch((error) => console.warn("Conflict draft save failed", error));
recordActivity("record-conflict", "Stale record update blocked", `${registry.tableId} ${modalState.recordIdentity} changed after the editor opened.`, "Conflict", { tableId: registry.tableId, recordIdentity: modalState.recordIdentity, expectedVersion: modalState.expectedVersion, currentVersion });
showToast("Version conflict", "The update was blocked, but your attempted edits were preserved under Profile > Synchronization.", "warning");
return;
}
}
Object.assign(targetRecord, updatedEntries, {
sourceSystem: updatedEntries.sourceSystem || "Profile-local workspace",
syncStatus: options.submitRemote ? "Queued" : "Local only",
effectiveAt: updatedEntries.effectiveAt || savedAt,
organizationId: updatedEntries.organizationId || getTenantId(),
version: Number(targetRecord.version || 1) + 1,
updatedBy: activeProfile.profileId,
updatedAt: savedAt,
__localUpdatedAt: savedAt
});
if (modalState.isLocalRecord) {
const localIndex = state.addedRecords.findIndex((record) => record.__localRecordId === targetRecord.__localRecordId);
if (localIndex >= 0) {
state.addedRecords[localIndex] = targetRecord;
}
} else {
state.updates[modalState.recordIdentity] = stripLocalMetadata(targetRecord);
}
writeLocalTableState(registry.tableId, state);
savedRecord = targetRecord;
savedIdentity = modalState.recordIdentity;
}
} catch (error) {
console.error("Local record save failed", error);
showToast("Save failed", "This browser could not store the local record. Check storage permissions and try again.", "danger");
return;
}
refreshConnectedTableState(registry.tableId);
const cleanRecord = stripLocalMetadata(savedRecord || updatedEntries);
persistVeteranContext(buildVeteranContextFromRecord(cleanRecord));
recordActivity(isCreate ? "record-create" : "record-update", isCreate ? "Record created" : "Record updated", `${registry.tableId} ${savedIdentity} was saved as version ${cleanRecord.version || 1}.`, "Local", { tableId: registry.tableId, recordIdentity: savedIdentity, version: cleanRecord.version || 1, organizationId: cleanRecord.organizationId || getTenantId() });
await storageService.putDurable(activeProfile.profileId, "versioned-records", `${registry.tableId}:${savedIdentity}`, cleanRecord).catch((error) => {
console.warn("Versioned record IndexedDB save failed", error);
});
let remoteResult = null;
if (options.submitRemote) {
const primaryKey = getRecordPrimaryKey(registry.tableId, cleanRecord);
if (!primaryKey) {
showToast("Submission blocked", "A generated primary key is required before this intake can be submitted.", "danger");
return;
}
remoteResult = await submitRemoteOperation(isCreate ? "intake-record-create" : "intake-record-update", {
tenantId: cleanRecord.organizationId || getTenantId(),
tableId: registry.tableId,
primaryKey,
recordIdentity: savedIdentity,
recordVersion: cleanRecord.version || 1,
expectedPreviousVersion: isCreate ? 0 : modalState.expectedVersion,
record: cleanRecord
}, isCreate ? "Intake record submitted" : "Record update submitted");
const effectiveIndex = isCreate
? (tableRegistry[registry.tableId]?.rows || []).findIndex((row) => row.__localRecordId === savedRecord?.__localRecordId)
: modalState.rowIndex;
persistRecordPatch(registry.tableId, savedRecord, Math.max(0, effectiveIndex), {
syncStatus: remoteResult.ok ? "Accepted" : "Queued",
remoteOperationId: remoteResult.operationId || "",
remoteReceipt: remoteResult.rowKey || ""
});
refreshConnectedTableState(registry.tableId);
}
if (options.submitRemote && !remoteResult?.ok) {
showToast("Saved locally; remote submission pending", "The local record was preserved and the failed remote operation is available in Profile > Synchronization.", "warning");
} else {
showToast(options.submitRemote ? "Saved and submitted" : "Saved locally", options.submitRemote ? "The record was saved locally and accepted by the remote API." : "The record remains local to this browser profile until you choose Save and submit.", "success");
}
if (modalInstance) {
modalInstance.hide();
}
modalState = null;
}
function resetLocalTable(tableId) {
const registry = tableRegistry[tableId];
if (!registry) {
return;
}
storageService.removeProfile(activeProfile.profileId, getLocalTableStorageKey(tableId));
const hostedRows = cloneRows(registry.hostedRows);
tableSourceRows[tableId].rows = hostedRows;
registry.rows = hostedRows;
registry.sortState = { key: null, direction: "ascending" };
rerenderTable(tableId);
showToast("Hosted data restored", "Local additions and overrides for this table were cleared for the active profile.", "success");
}
function rerenderTable(tableId) {
const registry = tableRegistry[tableId];
if (!registry || !registry.table) {
return;
}
const columns = getTableColumns(tableId);
registry.table.tBodies[0].innerHTML = registry.rows.map((row, index) => renderRow(row, columns, tableId, index)).join("");
bindTableInteractions(tableId, registry.rows);
if (registry.sortState && registry.sortState.key) {
registry.rows.sort((left, right) => compareValues(left[registry.sortState.key], right[registry.sortState.key], registry.sortState.direction));
registry.table.tBodies[0].innerHTML = registry.rows.map((row, index) => renderRow(row, columns, tableId, index)).join("");
bindTableInteractions(tableId, registry.rows);
return;
}
if (typeof registry.applyFilters === "function") {
registry.applyFilters();
}
}
function getTableColumns(tableId) {
const columnMap = {
homeRequests: [
{ key: "id", label: "Request ID" },
{ key: "customerReferenceNo", label: "Customer Reference No#" },
{ key: "veteran", label: "Veteran" },
{ key: "type", label: "Request Type" },
{ key: "location", label: "Location" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "status", label: "Status", formatter: statusPill }
],
requestTable: [
{ key: "id", label: "Request ID" },
{ key: "customerReferenceNo", label: "Customer Reference No#" },
{ key: "veteran", label: "Veteran" },
{ key: "type", label: "Type" },
{ key: "location", label: "Location" },
{ key: "guests", label: "Guests" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "status", label: "Status", formatter: statusPill }
],
providerTable: [
{ key: "name", label: "Provider" },
{ key: "type", label: "Type" },
{ key: "addressLine1", label: "Street Address" },
{ key: "city", label: "Municipality" },
{ key: "county", label: "County" },
{ key: "availableUnits", label: "Available Units" },
{ key: "accessibleRooms", label: "Accessible Units" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "contact", label: "Primary Contact" },
{ key: "lastInventoryCheck", label: "Inventory Confirmed", formatter: dateTimeFormatter }
],
caseTable: [
{ key: "caseId", label: "Case ID" },
{ key: "customerReferenceNo", label: "Customer Reference No#" },
{ key: "veteran", label: "Veteran" },
{ key: "manager", label: "Case Manager" },
{ key: "provider", label: "Provider" },
{ key: "phase", label: "Current Phase" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "nextStep", label: "Next Step" },
{ key: "eta", label: "ETA" }
],
reportTable: [
{ key: "reportId", label: "Report ID" },
{ key: "month", label: "Month" },
{ key: "region", label: "Region" },
{ key: "requests", label: "Requests" },
{ key: "placements", label: "Placements" },
{ key: "averageHours", label: "Avg Hours" },
{ key: "activeStays", label: "Active Stays" },
{ key: "cost", label: "Cost" }
],
placementTable: [
{ key: "placementId", label: "Placement ID" },
{ key: "veteran", label: "Veteran" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "assignedOwner", label: "Case Manager" },
{ key: "provider", label: "Provider" },
{ key: "holdStatus", label: "Hold" },
{ key: "approvalStatus", label: "Approval" },
{ key: "reservationNumber", label: "Reservation" },
{ key: "status", label: "Status", formatter: statusPill }
],
veteranTable: [
{ key: "veteranId", label: "Veteran ID" },
{ key: "veteranName", label: "Veteran" },
{ key: "householdId", label: "Household" },
{ key: "currentHousing", label: "Housing Status" },
{ key: "eligibilityStatus", label: "Eligibility", formatter: statusPill },
{ key: "activePrograms", label: "Active Program" },
{ key: "responsibleProvider", label: "Responsible Provider" },
{ key: "coordinatedEntryStatus", label: "CE Status", formatter: statusPill },
{ key: "duplicateStatus", label: "Duplicate Review" }
],
assessmentTable: [
{ key: "assessmentId", label: "Assessment ID" },
{ key: "veteranId", label: "Veteran ID" },
{ key: "veteranName", label: "Veteran" },
{ key: "housingCrisis", label: "Housing Crisis" },
{ key: "vulnerabilityScore", label: "Score" },
{ key: "programEligibility", label: "Eligibility" },
{ key: "finalPriority", label: "Final Priority", formatter: priorityPill },
{ key: "referralDecision", label: "Referral Decision" },
{ key: "status", label: "Status", formatter: statusPill }
],
consentTable: [
{ key: "consentId", label: "Consent ID" },
{ key: "veteranId", label: "Veteran ID" },
{ key: "veteranName", label: "Veteran" },
{ key: "permittedOrganization", label: "Permitted Organization" },
{ key: "informationCategories", label: "Information Categories" },
{ key: "purpose", label: "Purpose" },
{ key: "expirationDate", label: "Expires" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "disclosureCount", label: "Disclosures" }
],
unitTable: [
{ key: "unitId", label: "Unit ID" },
{ key: "providerId", label: "Provider ID" },
{ key: "providerName", label: "Provider" },
{ key: "unitType", label: "Unit Type" },
{ key: "county", label: "County" },
{ key: "accessibility", label: "Accessibility" },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "holdExpiresAt", label: "Hold Expires", formatter: dateTimeFormatter },
{ key: "conflictStatus", label: "Conflict" }
],
partnerOperationsTable: [
{ key: "coordinationId", label: "Work Item" },
{ key: "workType", label: "Workflow" },
{ key: "placementId", label: "Placement" },
{ key: "veteranName", label: "Veteran" },
{ key: "providerName", label: "Provider" },
{ key: "owner", label: "Owner" },
{ key: "priority", label: "Priority", formatter: priorityPill },
{ key: "actionDeadline", label: "Deadline", formatter: dateTimeFormatter },
{ key: "status", label: "Status", formatter: statusPill },
{ key: "actionOutcome", label: "Outcome" },
{ key: "nextAction", label: "Next Action" }
],
};
const columns = columnMap[tableId] || [];
return columns.length
? [...columns, { key: "updatedAt", label: "Last Updated", formatter: dateTimeFormatter }]
: columns;
}
function getRecordDetails(kind) {
if (kind === "provider") {
return {
title: "Provider readiness overview",
body: createEditableRecordMarkup({
"Accessible inventory": "Prioritize accessible = Yes for medical and mobility-related placements.",
"Service animal ready": "Use provider notes and status to confirm policy support before assignment.",
"Shuttle support": "Shuttle-enabled partners should be preferred for VA or hospital travel.",
"Escalations": "Waitlist or occupied providers can trigger alternate routing."
}),
toast: "Provider action captured."
};
}
if (kind === "case") {
return {
title: "Case review workflow",
body: createEditableRecordMarkup({
"Step 1": "Verify veteran profile, documents, urgency, and consent.",
"Step 2": "Search hotel or housing inventory against location, family size, dates, and accessibility.",
"Step 3": "Approve placement, notify veteran and provider, and capture check-in details.",
"Step 4": "Track check-in, extension, checkout, invoice routing, and case closure outcomes."
}),
toast: "Case workflow acknowledged."
};
}
return {
title: "Veteran intake requirements",
body: createEditableRecordMarkup({
"Required fields": "Request type, accommodation type, city, dates, guests, urgency, and consent",
"Helpful documents": "VA ID, DD214, referral information, appointment notes, and emergency context",
"Special needs": "Accessibility, transportation, family size, and service animal status"
}),
toast: "Request review opened."
};
}
function exportTableToCsv(tableId) {
const table = document.getElementById(tableId);
if (!table) {
return;
}
const visibleRows = Array.from(table.rows).filter((row) => !row.hidden);
const lines = visibleRows.map((row) => Array.from(row.cells).map((cell) => {
const text = cell.textContent.replace(/\s+/g, " ").trim().replace(/"/g, "\"\"");
return `"${text}"`;
}).join(","));
const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `${tableId}.csv`;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
function showToast(title, message, tone) {
const container = document.getElementById("toastStack");
if (!container) {
return;
}
const palette = {
primary: "text-bg-primary",
success: "text-bg-success",
info: "text-bg-info",
warning: "text-bg-warning",
danger: "text-bg-danger"
};
const toast = document.createElement("div");
toast.className = `toast align-items-center border-0 ${palette[tone] || "text-bg-primary"}`;
toast.setAttribute("role", "status");
toast.setAttribute("aria-live", "polite");
toast.setAttribute("aria-atomic", "true");
toast.innerHTML = `
${escapeHtml(title)}
${escapeHtml(message)}
`;
container.appendChild(toast);
const instance = new window.bootstrap.Toast(toast, { delay: 2800 });
instance.show();
toast.addEventListener("hidden.bs.toast", () => toast.remove());
}
function linkFormatter(value) {
const url = String(value || "");
return `Open `;
}
function objectToDetailMarkup(record) {
return `
${Object.entries(record).map(([key, value]) => `
${escapeHtml(key)}
${escapeHtml(String(value))}
`).join("")}
`;
}
function renderRecordWorkspace(tableId, rowData) {
Object.keys(connectedModalRecords).forEach((key) => delete connectedModalRecords[key]);
Object.keys(connectedModalTables).forEach((key) => delete connectedModalTables[key]);
const record = stripLocalMetadata(rowData);
const workspaceId = `record-workspace-${slugify(tableId)}`;
const groups = getConnectedRecordGroups(tableId, rowData);
const tabButtons = [
`Primary record `,
...groups.map((group) => `${escapeHtml(group.label)} ${group.total} `)
];
const connectedPanes = groups.length
? groups.map((group) => renderConnectedRecordPane(workspaceId, group)).join("")
: `
No connected datasource records were found for this item.
`;
if (!groups.length) {
tabButtons.push(`Connected data `);
}
return `
Connected datasource workspace
Review and edit related records without leaving this view.
${groups.reduce((total, group) => total + group.total, 0)} linked
${createEditableRecordMarkup(record, { idPrefix: `${workspaceId}-primary`, tableId })}
${connectedPanes}
`;
}
function getConnectedRecordGroups(primaryTableId, primaryRecord) {
const primaryDatasource = tableDatasources[primaryTableId];
const requests = getEffectiveDatasourceRows("requests");
const cases = getEffectiveDatasourceRows("cases");
const veterans = getEffectiveDatasourceRows("veterans");
const operations = getEffectiveDatasourceRows("partnerOperations");
let requestId = primaryRecord.requestId || (String(primaryRecord.id || "").startsWith("REQ-") ? primaryRecord.id : "");
let caseId = primaryRecord.caseId || (String(primaryRecord.id || "").startsWith("CASE-") ? primaryRecord.id : "");
let providerId = primaryRecord.providerId || (String(primaryRecord.id || "").startsWith("PROV-") ? primaryRecord.id : "");
let veteranId = primaryRecord.veteranId || (String(primaryRecord.id || "").startsWith("VET-") ? primaryRecord.id : "");
let placementId = primaryRecord.placementId || "";
let customerReferenceNo = primaryRecord.customerReferenceNo || "";
const linkedOperation = primaryDatasource === "partnerOperations" ? primaryRecord : operations.find((record) =>
(placementId && record.placementId === placementId)
|| (caseId && record.caseId === caseId)
|| (requestId && record.requestId === requestId)
|| (veteranId && record.veteranId === veteranId));
const linkedRequest = requests.find((record) => record.id === (requestId || linkedOperation?.requestId))
|| requests.find((record) => record.caseId === (caseId || linkedOperation?.caseId));
const linkedCase = cases.find((record) => record.caseId === (caseId || linkedOperation?.caseId || linkedRequest?.caseId))
|| cases.find((record) => record.requestId === (requestId || linkedOperation?.requestId || linkedRequest?.id));
const linkedVeteran = veterans.find((record) => record.veteranId === (veteranId || linkedOperation?.veteranId))
|| veterans.find((record) => record.requestId === (requestId || linkedOperation?.requestId || linkedRequest?.id))
|| veterans.find((record) => customerReferenceNo && record.customerReferenceNo === customerReferenceNo);
requestId ||= linkedOperation?.requestId || linkedRequest?.id || linkedCase?.requestId || linkedVeteran?.requestId || "";
caseId ||= linkedOperation?.caseId || linkedCase?.caseId || linkedRequest?.caseId || "";
providerId ||= linkedOperation?.providerId || linkedCase?.providerId || linkedRequest?.providerId || linkedVeteran?.responsibleProviderId || "";
veteranId ||= linkedOperation?.veteranId || linkedVeteran?.veteranId || "";
placementId ||= linkedOperation?.placementId || "";
customerReferenceNo ||= linkedRequest?.customerReferenceNo || linkedCase?.customerReferenceNo || linkedVeteran?.customerReferenceNo || "";
const reportMonth = primaryRecord.month || String(primaryRecord.reportDate || "").slice(0, 7);
const reportRegion = primaryRecord.region || "";
const relationshipMatches = (record, dataKey) => {
if (dataKey === "requests") {
if (requestId) {
return record.id === requestId;
}
if (customerReferenceNo) {
return record.customerReferenceNo === customerReferenceNo;
}
if (primaryDatasource === "providers") {
return providerId ? record.providerId === providerId : Boolean(primaryRecord.city && record.location === primaryRecord.city);
}
return primaryDatasource === "reports" && reportMonth && String(record.createdAt || record.updatedAt || "").startsWith(reportMonth);
}
if (dataKey === "cases") {
if (caseId) {
return record.caseId === caseId;
}
if (requestId) {
return record.requestId === requestId;
}
if (customerReferenceNo) {
return record.customerReferenceNo === customerReferenceNo;
}
if (primaryDatasource === "providers") {
return providerId ? record.providerId === providerId : Boolean(primaryRecord.city && record.location === primaryRecord.city);
}
return primaryDatasource === "reports" && reportMonth && String(record.createdAt || record.updatedAt || "").startsWith(reportMonth);
}
if (dataKey === "providers") {
if (providerId) {
return record.providerId === providerId;
}
if (primaryRecord.provider) {
return record.name === primaryRecord.provider;
}
return primaryDatasource === "reports" && reportRegion && record.region === reportRegion;
}
if (dataKey === "veterans") {
return (veteranId && record.veteranId === veteranId)
|| (requestId && record.requestId === requestId)
|| (customerReferenceNo && record.customerReferenceNo === customerReferenceNo);
}
if (dataKey === "coordinatedEntry" || dataKey === "consents") {
return veteranId && record.veteranId === veteranId;
}
if (dataKey === "units") {
return (providerId && record.providerId === providerId)
|| (caseId && record.caseId === caseId)
|| (placementId && record.placementId === placementId);
}
if (dataKey === "partnerOperations") {
if (placementId) return record.placementId === placementId;
if (caseId) return record.caseId === caseId;
if (requestId) return record.requestId === requestId;
if (veteranId) return record.veteranId === veteranId;
return primaryDatasource === "providers" && providerId && record.providerId === providerId;
}
return false;
};
const definitions = [
{ key: "requests", label: "Veteran requests", tableId: "requestTable" },
{ key: "cases", label: "Cases", tableId: "caseTable" },
{ key: "providers", label: "Providers", tableId: "providerTable" },
{ key: "veterans", label: "Veteran 360", tableId: "veteranTable" },
{ key: "coordinatedEntry", label: "CE assessments", tableId: "assessmentTable" },
{ key: "consents", label: "Consents", tableId: "consentTable" },
{ key: "units", label: "Beds and units", tableId: "unitTable" },
{ key: "partnerOperations", label: "Agent operations", tableId: "partnerOperationsTable" }
];
return definitions.map((definition) => {
const columns = getTableColumns(definition.tableId);
const primaryIdentity = primaryDatasource === definition.key
? getRecordIdentity(primaryRecord, columns, 0)
: "";
const matches = getEffectiveDatasourceRows(definition.key)
.filter((record, index) => relationshipMatches(record, definition.key)
&& (!primaryIdentity || getRecordIdentity(record, columns, index) !== primaryIdentity))
.sort((left, right) => String(right.updatedAt || right.createdAt || "").localeCompare(String(left.updatedAt || left.createdAt || "")));
return { ...definition, records: matches.slice(0, 100), total: matches.length };
}).filter((group) => group.total > 0);
}
function getEffectiveDatasourceRows(dataKey) {
const tableId = datasourceTables[dataKey];
const hostedRows = cloneRows(tableStore[dataKey] || []);
return tableId ? resolveTableRows(tableId, hostedRows, getTableColumns(tableId)) : hostedRows;
}
function renderConnectedRecordPane(workspaceId, group) {
const content = group.total > 1
? renderConnectedRecordTable(workspaceId, group)
: renderConnectedRecordCard(workspaceId, group, group.records[0], 0);
return `
${content}
`;
}
function registerConnectedModalRecord(workspaceId, group, record, index, tableKey = "") {
const token = `${workspaceId}-${group.key}-${index}-${slugify(getConnectedRecordHeading(group.tableId, record))}`;
connectedModalRecords[token] = {
workspaceId,
groupKey: group.key,
groupLabel: group.label,
tableId: group.tableId,
tableKey,
recordIdentity: getRecordIdentity(record, getTableColumns(group.tableId), index),
record
};
return token;
}
function renderConnectedRecordCard(workspaceId, group, record, index, existingToken = "") {
const columns = getTableColumns(group.tableId);
const identity = getRecordIdentity(record, columns, index);
const localRecordId = record.__localRecordId || "";
const token = existingToken || registerConnectedModalRecord(workspaceId, group, record, index);
return `
${escapeHtml(group.label)}
${escapeHtml(getConnectedRecordHeading(group.tableId, record))}
Local
${createEditableRecordMarkup(stripLocalMetadata(record), {
connected: true,
idPrefix: `${workspaceId}-${group.key}-${slugify(token)}`,
tableId: group.tableId,
recordIdentity: identity,
localRecordId,
recordToken: token
})}
`;
}
function renderConnectedRecordTable(workspaceId, group) {
const tableKey = `${workspaceId}-${group.key}-records`;
const columns = getConnectedTableColumns(group.tableId);
const filterKey = columns.find((column) => ["status", "phase", "priority", "type", "workType", "region"].includes(column.key))?.key || columns[0]?.key || "status";
const tokens = group.records.map((record, index) => registerConnectedModalRecord(workspaceId, group, record, index, tableKey));
const filterOptions = [...new Set(group.records.map((record) => record[filterKey]).filter((value) => value !== undefined && value !== ""))];
connectedModalTables[tableKey] = { tableKey, tokens, columns, filterKey, sortState: { key: null, direction: "ascending" } };
return `
${group.total > group.records.length ? `Showing the ${group.records.length} most recently updated of ${group.total} connected records.
` : ""}
`;
}
function getConnectedTableColumns(tableId) {
const keyMap = {
requestTable: ["id", "veteran", "location", "priority", "status"],
caseTable: ["caseId", "veteran", "provider", "phase", "status"],
providerTable: ["providerId", "name", "city", "availableUnits", "status"],
reportTable: ["reportId", "month", "region", "requests", "placements"],
placementTable: ["placementId", "veteran", "provider", "approvalStatus", "status"],
veteranTable: ["veteranId", "veteranName", "currentHousing", "eligibilityStatus", "coordinatedEntryStatus"],
assessmentTable: ["assessmentId", "veteranId", "finalPriority", "referralDecision", "status"],
consentTable: ["consentId", "veteranId", "permittedOrganization", "purpose", "status"],
unitTable: ["unitId", "providerId", "unitType", "accessibility", "status"],
partnerOperationsTable: ["coordinationId", "workType", "veteranName", "actionDeadline", "status"]
};
const tableColumns = getTableColumns(tableId);
const allowedKeys = keyMap[tableId];
return allowedKeys
? tableColumns.filter((column) => allowedKeys.includes(column.key))
: tableColumns.slice(0, 5);
}
function renderConnectedTableRows(tableKey) {
const registry = connectedModalTables[tableKey];
if (!registry) {
return "";
}
return registry.tokens.map((token) => {
const record = connectedModalRecords[token]?.record || {};
return `
Edit
${registry.columns.map((column) => `${column.formatter ? column.formatter(record[column.key]) : escapeHtml(String(record[column.key] ?? ""))} `).join("")}
`;
}).join("");
}
function getConnectedRecordHeading(tableId, record) {
const headings = {
requestTable: [record.id || "Request", record.veteran || "Veteran"],
caseTable: [record.caseId || "Case", record.veteran || "Veteran"],
providerTable: [record.providerId || "Provider", record.name || "Provider"],
reportTable: [record.reportId || "Report", record.month || record.region || "Reporting period"],
placementTable: [record.placementId || "Placement", record.veteran || "Veteran"],
veteranTable: [record.veteranId || "Veteran", record.veteranName || "Veteran"],
assessmentTable: [record.assessmentId || "Assessment", record.veteranName || record.veteranId || "Veteran"],
consentTable: [record.consentId || "Consent", record.veteranName || record.veteranId || "Veteran"],
unitTable: [record.unitId || "Unit", record.providerName || record.providerId || "Provider"],
partnerOperationsTable: [record.coordinationId || "Work item", record.veteranName || "Veteran"]
};
const parts = headings[tableId] || ["Connected record"];
return parts.filter(Boolean).join(" - ");
}
function createEditableRecordMarkup(record, options = {}) {
const idPrefix = options.idPrefix || "modal-primary";
const editableRecord = withRequiredModalFields(options.tableId, record);
const editableFields = Object.entries(editableRecord).filter(([key]) => !scenarioFormFieldKeys.has(String(key).toLowerCase()));
const recordContext = options.connected ? "connected" : "primary";
const formAttributes = options.connected
? `data-connected-record-form data-record-form-context="connected" data-table-id="${escapeHtml(options.tableId)}" data-connected-table-id="${escapeHtml(options.tableId)}" data-connected-record-identity="${escapeHtml(options.recordIdentity)}" data-connected-local-id="${escapeHtml(options.localRecordId || "")}" data-connected-record-token="${escapeHtml(options.recordToken || "")}"`
: `data-editable-record-form data-record-form-context="primary" data-table-id="${escapeHtml(options.tableId || "")}"`;
return `
${options.connected ? "Connected record" : "Primary record"}
Sample values never replace the record ID or managed timestamps.
Load sample data
${editableFields.map(([key, value]) => renderEditableField(key, value, idPrefix, options)).join("")}
${options.connected ? `Connected record actions: these buttons update only this related record. They do not save the primary record.
Save connected record locally Save connected record & submit
` : ""}
`;
}
function getSampleRecordForForm(form) {
const tableId = form?.dataset.tableId || form?.dataset.connectedTableId || modalState?.tableId || "";
const datasource = tableDatasources[tableId];
const rows = datasource ? getEffectiveDatasourceRows(datasource) : [];
if (!rows.length) return null;
const currentIdentity = getRecordPrimaryKey(tableId, Object.fromEntries(new FormData(form).entries()))?.value || "";
return rows.find((row) => getRecordPrimaryKey(tableId, row)?.value !== currentIdentity) || rows[0];
}
function fillFormWithSampleRecord(form, sampleRecord, contextLabel = "record") {
if (!form || !sampleRecord) {
showToast("Sample unavailable", "No sample record is available for this form.", "warning");
return;
}
const tableId = form.dataset.tableId || form.dataset.connectedTableId || modalState?.tableId || "";
const primaryKey = generatedIdDefinitions[tableId]?.key;
const protectedFields = new Set([primaryKey, "createdAt", "updatedAt", "effectiveAt", "version"].filter(Boolean));
Array.from(form.elements).forEach((control) => {
if (!control.name || protectedFields.has(control.name) || control.readOnly || control.disabled) return;
const value = sampleRecord[control.name];
if (value === undefined || value === null) return;
if (control.type === "checkbox" || control.type === "radio") {
control.checked = String(control.value) === String(value) || value === true;
} else if (control.tagName === "SELECT") {
const optionExists = Array.from(control.options).some((option) => option.value === String(value));
if (optionExists) control.value = String(value);
} else {
control.value = String(value);
}
control._syncTypeahead?.();
control.dispatchEvent(new Event("input", { bubbles: true }));
control.dispatchEvent(new Event("change", { bubbles: true }));
});
form.classList.remove("was-validated");
clearStaleRecordValidation(form);
showToast("Sample data loaded", `Realistic ${contextLabel} values are ready for review. The record ID and managed timestamps were preserved.`, "success");
}
function bindSampleDataActions(root) {
root?.querySelectorAll("[data-load-record-sample]:not([data-sample-bound])").forEach((button) => {
button.dataset.sampleBound = "true";
button.addEventListener("click", () => {
const form = button.closest("form");
fillFormWithSampleRecord(form, getSampleRecordForForm(form), button.dataset.recordContext === "connected" ? "connected record" : "primary record");
});
});
}
function withRequiredModalFields(tableId, record) {
const assuranceFields = {
sourceSystem: record.sourceSystem || (record.__localRecordId || record.__localOverride ? "Profile-local workspace" : "Hosted baseline"),
verificationStatus: record.verificationStatus || "Unverified simulation",
effectiveAt: record.effectiveAt || record.updatedAt || record.createdAt || new Date().toISOString(),
syncStatus: record.syncStatus || (record.__localRecordId || record.__localOverride ? "Local only" : "Published baseline"),
version: Number(record.version || 1)
};
if (tableId !== "providerTable") return { ...assuranceFields, ...record };
return {
providerId: "",
name: "",
type: "",
addressLine1: "",
municipality: "",
city: "",
county: "",
state: "NJ",
postalCode: "",
capacity: "",
availableUnits: "",
accessibleRooms: "",
status: "",
contact: "",
contactEmail: "",
contactPhone: "",
lastInventoryCheck: "",
...assuranceFields,
...record
};
}
function renderEditableField(key, value, idPrefix = "modal", options = {}) {
const fieldId = `${idPrefix}-${slugify(key)}`;
const stringValue = String(value ?? "");
const normalizedKey = String(key).toLowerCase();
const selectOptions = getFieldOptions(key, value);
const isLongText = stringValue.length > 80 || /\n/.test(stringValue);
const inputType = inferInputType(key, stringValue);
const inputValue = inputType === "datetime-local" ? stringValue.slice(0, 16) : stringValue;
const isSystemTimestamp = normalizedKey === "createdat" || normalizedKey === "updatedat";
const isReadOnly = isSystemTimestamp || (Array.isArray(options.readOnlyKeys) && options.readOnlyKeys.includes(key));
const isRelationshipField = Boolean(getRelationshipFieldDefinition(normalizedKey));
const readOnlyHelp = isSystemTimestamp
? "Managed automatically by BeaReponseCare and included in the saved JSON payload."
: "Generated from the current record sequence.";
const fieldMarkup = isReadOnly
? `${escapeHtml(readOnlyHelp)}
`
: isRelationshipField || selectOptions.length
? renderEditableSelect(fieldId, key, stringValue, selectOptions)
: isLongText
? `${escapeHtml(stringValue)} `
: ` `;
return `
${escapeHtml(formatFieldLabel(key))}
${fieldMarkup}
`;
}
function formatFieldLabel(key) {
if (String(key).toLowerCase() === "assignedowner") {
return "Case Manager";
}
const acronyms = new Map([
["id", "ID"], ["sla", "SLA"], ["ce", "CE"], ["api", "API"],
["sms", "SMS"], ["va", "VA"], ["pii", "PII"], ["url", "URL"]
]);
return String(key || "Field")
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[_-]+/g, " ")
.trim()
.split(/\s+/)
.map((word) => acronyms.get(word.toLowerCase()) || `${word.charAt(0).toUpperCase()}${word.slice(1)}`)
.join(" ");
}
function bindConnectedTableWorkspaces(root) {
if (!root) {
return;
}
root.querySelectorAll("[data-connected-table-workspace]").forEach((workspace) => {
const tableKey = workspace.dataset.connectedTableWorkspace;
const registry = connectedModalTables[tableKey];
const table = workspace.querySelector("[data-connected-record-table]");
const search = workspace.querySelector("[data-connected-search]");
const filter = workspace.querySelector("[data-connected-filter]");
const count = workspace.querySelector("[data-connected-count]");
if (!registry || !table) {
return;
}
const applyFilters = () => {
const searchTerm = String(search?.value || "").trim().toLowerCase();
const filterValue = String(filter?.value || "");
let visibleCount = 0;
Array.from(table.tBodies[0].rows).forEach((row) => {
const record = connectedModalRecords[row.dataset.connectedToken]?.record || {};
const searchMatch = !searchTerm || Object.values(record).join(" ").toLowerCase().includes(searchTerm);
const filterMatch = !filterValue || String(record[registry.filterKey] ?? "") === filterValue;
row.hidden = !(searchMatch && filterMatch);
if (!row.hidden) {
visibleCount += 1;
}
});
if (count) {
count.textContent = `${visibleCount} of ${registry.tokens.length} records`;
}
};
const renderRows = () => {
table.tBodies[0].innerHTML = renderConnectedTableRows(tableKey);
applyFilters();
};
registry.applyFilters = applyFilters;
registry.renderRows = renderRows;
search?.addEventListener("input", applyFilters);
wireTableSearchTypeahead(search, () => registry.tokens.map((token) => connectedModalRecords[token]?.record || {}), registry.columns, tableKey);
filter?.addEventListener("change", applyFilters);
workspace.querySelector("[data-connected-export]")?.addEventListener("click", () => {
if (!canPerform("export")) {
showToast("Permission required", `${activeProfile.role} cannot export connected records.`, "danger");
recordActivity("connected-export", "Connected export blocked", `${table.id} was not exported because the active demo role lacks permission.`, "Blocked", { tableId: table.id });
return;
}
exportTableToCsv(table.id);
recordActivity("connected-export", "Connected records exported", `${table.id} was exported as a CSV file.`, "Completed", { tableId: table.id });
showToast("CSV exported", `Downloaded ${table.id}.csv`, "success");
});
table.querySelectorAll("[data-connected-sort]").forEach((button) => {
button.addEventListener("click", () => {
const sortKey = button.dataset.sortKey;
const direction = registry.sortState.key === sortKey && registry.sortState.direction === "ascending" ? "descending" : "ascending";
registry.sortState = { key: sortKey, direction };
registry.tokens.sort((leftToken, rightToken) => compareValues(
connectedModalRecords[leftToken]?.record?.[sortKey],
connectedModalRecords[rightToken]?.record?.[sortKey],
direction
));
workspace.querySelectorAll("[data-connected-sort]").forEach((sortButton) => {
const active = sortButton === button;
sortButton.setAttribute("aria-sort", active ? direction : "none");
const icon = sortButton.querySelector("i");
if (icon) {
icon.className = active
? `bi ${direction === "ascending" ? "bi-sort-up" : "bi-sort-down"} ms-1`
: "bi bi-arrow-down-up ms-1";
}
});
renderRows();
});
});
table.addEventListener("click", (event) => {
const editButton = event.target.closest("[data-edit-connected-record]");
if (editButton) {
openConnectedRecordEditTab(editButton.dataset.editConnectedRecord);
}
});
applyFilters();
});
}
function openConnectedRecordEditTab(token) {
const connection = connectedModalRecords[token];
const workspace = recordModalBody.querySelector("[data-record-workspace]");
if (!connection || !workspace) {
showToast("Edit unavailable", "The connected record could not be opened in this modal.", "danger");
return;
}
const tabId = `${connection.workspaceId}-edit-${slugify(token)}`;
let tabButton = workspace.querySelector(`#${tabId}-tab`);
if (!tabButton) {
const tabList = workspace.querySelector(".record-workspace-tabs");
const tabContent = workspace.querySelector(":scope > .tab-content");
const heading = getConnectedRecordHeading(connection.tableId, connection.record);
tabList.insertAdjacentHTML("beforeend", `
Edit ${escapeHtml(heading)}
`);
tabContent.insertAdjacentHTML("beforeend", `
${renderConnectedRecordCard(connection.workspaceId, {
key: connection.groupKey,
label: connection.groupLabel,
tableId: connection.tableId
}, connection.record, 0, token)}
`);
tabButton = workspace.querySelector(`#${tabId}-tab`);
const editPane = workspace.querySelector(`#${tabId}`);
wireModalTypeaheadDropdowns(editPane);
bindLinkedDatasourceFields(editPane);
bindSampleDataActions(editPane);
bindConnectedRecordForms(editPane);
workspace.querySelector(`[data-close-connected-edit-tab="${tabId}"]`)?.addEventListener("click", (event) => {
event.stopPropagation();
closeConnectedRecordEditTab(tabId, connection);
});
}
window.bootstrap.Tab.getOrCreateInstance(tabButton).show();
tabButton.scrollIntoView({ block: "nearest", inline: "end" });
}
function updateModalFooterForActiveRecordTab() {
const workspace = recordModalBody?.querySelector("[data-record-workspace]");
if (!workspace || !modalPrimaryAction) return;
const activePane = workspace.querySelector(":scope > .tab-content > .tab-pane.active");
const isPrimaryPane = Boolean(activePane?.id?.endsWith("-primary"));
modalPrimaryAction.classList.toggle("d-none", !isPrimaryPane);
modalRemoteAction?.classList.toggle("d-none", !isPrimaryPane);
}
function bindModalRecordTabActions() {
const workspace = recordModalBody?.querySelector("[data-record-workspace]");
if (!workspace) return;
workspace.querySelectorAll('[data-bs-toggle="tab"]').forEach((tab) => {
tab.addEventListener("shown.bs.tab", updateModalFooterForActiveRecordTab);
});
updateModalFooterForActiveRecordTab();
}
function closeConnectedRecordEditTab(tabId, connection) {
const workspace = recordModalBody.querySelector("[data-record-workspace]");
const tabItem = workspace?.querySelector(`[data-dynamic-edit-tab="${tabId}"]`);
const tabButton = workspace?.querySelector(`#${tabId}-tab`);
const tabPane = workspace?.querySelector(`#${tabId}`);
if (!workspace || !tabItem || !tabButton || !tabPane) {
return;
}
const removeTab = () => {
window.bootstrap.Tab.getInstance(tabButton)?.dispose();
tabPane.remove();
tabItem.remove();
showToast("Edit tab closed", "The connected record editor was removed from this modal.", "info");
};
if (tabButton.classList.contains("active")) {
const sourceTab = workspace.querySelector(`#${connection.workspaceId}-${connection.groupKey}-tab`)
|| workspace.querySelector(`#${connection.workspaceId}-primary-tab`);
sourceTab.addEventListener("shown.bs.tab", removeTab, { once: true });
window.bootstrap.Tab.getOrCreateInstance(sourceTab).show();
return;
}
removeTab();
}
function bindConnectedRecordForms(root) {
if (!root) {
return;
}
root.querySelectorAll("[data-connected-record-form]").forEach((form) => {
bindRecordValidationReset(form);
form.addEventListener("submit", (event) => event.preventDefault());
form.querySelector("[data-save-connected-record]")?.addEventListener("click", () => saveConnectedRecordForm(form));
form.querySelector("[data-submit-connected-record]")?.addEventListener("click", () => saveConnectedRecordForm(form, { submitRemote: true }));
});
}
async function saveConnectedRecordForm(form, options = {}) {
if (options.submitRemote && !validateRemoteProfileConfiguration("update")) {
return;
}
clearStaleRecordValidation(form);
if (!form.reportValidity()) {
showToast("Validation required", "Complete the connected record fields before saving.", "danger");
return;
}
const tableId = form.dataset.connectedTableId;
const recordIdentity = form.dataset.connectedRecordIdentity;
const localRecordId = form.dataset.connectedLocalId;
const connection = connectedModalRecords[form.dataset.connectedRecordToken];
if (!tableId || (!recordIdentity && !localRecordId)) {
showToast("Save failed", "The connected datasource identity is unavailable.", "danger");
return;
}
const savedAt = new Date().toISOString();
const expectedVersion = Number(connection?.record?.version || 1);
const updatedRecord = {
...Object.fromEntries(new FormData(form).entries()),
syncStatus: options.submitRemote ? "Queued" : "Local only",
organizationId: getTenantId(),
version: expectedVersion + 1,
updatedBy: activeProfile.profileId,
updatedAt: savedAt,
__localUpdatedAt: savedAt
};
if (!applyRecordValidation(form, tableId, { ...(connection?.record || {}), ...updatedRecord })) {
form.reportValidity();
return;
}
try {
const state = readLocalTableState(tableId);
if (versionedTableIds.has(tableId)) {
const persistedRecord = localRecordId
? state.addedRecords.find((record) => record.__localRecordId === localRecordId)
: state.updates[recordIdentity];
const currentVersion = Number(persistedRecord?.version || connection?.record?.version || 1);
if (currentVersion !== expectedVersion) {
const conflictId = `CONFLICT-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
await storageService.putDurable(activeProfile.profileId, "conflict-drafts", conflictId, {
conflictId,
tableId,
recordIdentity: recordIdentity || localRecordId,
expectedVersion,
currentVersion,
attemptedEdits: stripLocalMetadata(updatedRecord),
currentRecord: stripLocalMetadata(connection?.record || {}),
savedAt: new Date().toISOString()
}).catch((error) => console.warn("Connected conflict draft save failed", error));
recordActivity("record-conflict", "Connected stale update blocked", `${tableId} ${recordIdentity || localRecordId} changed after the tab opened.`, "Conflict", { tableId, recordIdentity: recordIdentity || localRecordId, expectedVersion, currentVersion });
showToast("Version conflict", "The update was blocked, but your attempted edits were preserved under Profile > Synchronization.", "warning");
return;
}
}
if (localRecordId) {
const localIndex = state.addedRecords.findIndex((record) => record.__localRecordId === localRecordId);
if (localIndex < 0) {
throw new Error("Connected local record was not found.");
}
state.addedRecords[localIndex] = { ...state.addedRecords[localIndex], ...updatedRecord };
} else {
state.updates[recordIdentity] = stripLocalMetadata(updatedRecord);
}
writeLocalTableState(tableId, state);
refreshConnectedTableState(tableId);
refreshConnectedModalRecord(form.dataset.connectedRecordToken, updatedRecord);
form.closest("[data-connected-record-card]")?.querySelector("[data-connected-local-badge]")?.classList.remove("d-none");
const updatedAtField = form.elements.namedItem("updatedAt");
if (updatedAtField) {
updatedAtField.value = savedAt.slice(0, 16);
}
showToast("Connected record saved", "The related datasource update is stored under this local profile.", "success");
recordActivity("connected-record-update", "Connected record updated", `${tableId} record ${recordIdentity || localRecordId} was updated locally.`, "Local", { tableId, recordIdentity: recordIdentity || localRecordId });
await storageService.putDurable(activeProfile.profileId, "connected-records", `${tableId}:${recordIdentity || localRecordId}`, stripLocalMetadata(updatedRecord)).catch((error) => {
console.warn("Connected record IndexedDB save failed", error);
});
if (options.submitRemote) {
const primaryKey = getRecordPrimaryKey(tableId, updatedRecord);
const remoteResult = await submitRemoteOperation("versioned-connected-record-upsert", {
tenantId: getTenantId(),
tableId,
primaryKey,
recordIdentity: recordIdentity || localRecordId,
recordVersion: updatedRecord.version,
expectedPreviousVersion: expectedVersion,
record: stripLocalMetadata(updatedRecord)
}, "Connected record submitted");
persistRecordPatch(tableId, localRecordId ? { ...updatedRecord, __localRecordId: localRecordId } : updatedRecord, 0, {
syncStatus: remoteResult.ok ? "Accepted" : "Queued",
remoteOperationId: remoteResult.operationId || "",
remoteReceipt: remoteResult.rowKey || ""
});
refreshConnectedTableState(tableId);
showToast(remoteResult.ok ? "Connected record saved and submitted" : "Connected record saved; submission pending", remoteResult.ok ? "The update is local and the remote API accepted it." : "The local update is preserved in the synchronization queue.", remoteResult.ok ? "success" : "warning");
}
} catch (error) {
console.error("Connected record save failed", error);
showToast("Save failed", "The connected record could not be stored in this browser.", "danger");
}
}
function refreshConnectedModalRecord(token, updatedRecord) {
const connection = connectedModalRecords[token];
if (!connection) {
return;
}
Object.values(connectedModalRecords).forEach((candidate) => {
if (candidate.tableId !== connection.tableId || candidate.recordIdentity !== connection.recordIdentity) {
return;
}
candidate.record = { ...candidate.record, ...updatedRecord, __localOverride: true };
const registry = connectedModalTables[candidate.tableKey];
if (registry && typeof registry.renderRows === "function") {
registry.renderRows();
}
});
}
function refreshConnectedTableState(tableId) {
const dataKey = tableDatasources[tableId];
if (!dataKey) {
return;
}
const hostedRows = cloneRows(tableStore[dataKey] || []);
const affectedTableIds = dataKey === "requests" ? ["requestTable", "homeRequests"] : [tableId];
affectedTableIds.forEach((affectedTableId) => {
const tableHostedRows = tableSourceRows[affectedTableId]?.hostedRows || hostedRows;
const rows = resolveTableRows(affectedTableId, tableHostedRows, getTableColumns(affectedTableId));
if (tableSourceRows[affectedTableId]) {
tableSourceRows[affectedTableId].hostedRows = cloneRows(tableHostedRows);
tableSourceRows[affectedTableId].rows = rows;
}
if (tableRegistry[affectedTableId]) {
tableRegistry[affectedTableId].hostedRows = cloneRows(tableHostedRows);
tableRegistry[affectedTableId].rows = rows;
tableRegistry[affectedTableId].sortState = { key: null, direction: "ascending" };
rerenderTable(affectedTableId);
}
});
if (tableId === "placementTable") {
searchInput?._refreshPlacementSearch?.();
}
}
function inferInputType(key, value) {
const normalizedKey = String(key).toLowerCase();
if (/(?:at|timestamp)$/.test(normalizedKey)) {
return "datetime-local";
}
if (normalizedKey.includes("date") || normalizedKey.includes("checkin") || normalizedKey.includes("checkout")) {
return "date";
}
if (normalizedKey === "month") {
return "month";
}
if (normalizedKey.includes("email")) {
return "email";
}
if (normalizedKey.includes("phone") || normalizedKey.includes("contact")) {
return "text";
}
if (!Number.isNaN(Number(value)) && value !== "") {
return "number";
}
return "text";
}
function renderEditableSelect(fieldId, key, value, options) {
const normalizedValue = normalizeOptionValue(value);
const relationshipLabels = getRelationshipOptionLabels(key);
return `
${options.map((option) => {
const optionValue = String(option);
const selected = normalizeOptionValue(optionValue) === normalizedValue ? " selected" : "";
return `${escapeHtml(relationshipLabels.get(optionValue) || optionValue)} `;
}).join("")}
`;
}
function getRelationshipOptionLabels(key) {
const normalizedKey = String(key).toLowerCase();
const definition = getRelationshipFieldDefinition(normalizedKey);
if (!definition) {
return new Map();
}
return new Map(getEffectiveDatasourceRows(definition.dataKey).map((record) => {
const id = String(record[definition.idKey] ?? "");
const name = String(definition.nameKeys.map((nameKey) => record[nameKey]).find((value) => value !== undefined && value !== "") ?? "");
return [id, name ? `${id} - ${name}` : id];
}).filter(([id]) => id));
}
function getRelationshipFieldDefinition(key) {
const definitions = {
requestid: { dataKey: "requests", idKey: "id", nameKeys: ["veteran", "veteranName"] },
caseid: { dataKey: "cases", idKey: "caseId", nameKeys: ["veteran", "veteranName"] },
providerid: { dataKey: "providers", idKey: "providerId", nameKeys: ["name", "providerName"] },
responsibleproviderid: { dataKey: "providers", idKey: "providerId", nameKeys: ["name", "providerName"] },
referredproviderid: { dataKey: "providers", idKey: "providerId", nameKeys: ["name", "providerName"] },
customerreferenceno: { dataKey: "requests", idKey: "customerReferenceNo", nameKeys: ["veteran", "veteranName"] },
veteranid: { dataKey: "veterans", idKey: "veteranId", nameKeys: ["veteranName", "veteran"] },
householdid: { dataKey: "veterans", idKey: "householdId", nameKeys: ["veteranName", "veteran"] },
placementid: { dataKey: "placements", idKey: "placementId", nameKeys: ["veteran", "veteranName"] },
assessmentid: { dataKey: "coordinatedEntry", idKey: "assessmentId", nameKeys: ["veteranName", "veteran"] },
consentid: { dataKey: "consents", idKey: "consentId", nameKeys: ["veteranName", "veteran"] },
unitid: { dataKey: "units", idKey: "unitId", nameKeys: ["unitName", "providerName", "provider"] },
coordinationid: { dataKey: "partnerOperations", idKey: "coordinationId", nameKeys: ["veteranName", "workType"] },
reportid: { dataKey: "reports", idKey: "reportId", nameKeys: ["name", "title"] }
};
return definitions[String(key).toLowerCase()] || null;
}
function wireModalTypeaheadDropdowns(root) {
if (!root) {
return;
}
root.querySelectorAll("select:not([data-typeahead-enhanced])").forEach((select, index) => {
if (select.multiple) {
return;
}
const selectId = select.id || `modal-select-${Date.now()}-${index}`;
const inputId = `${selectId}-typeahead`;
const menuId = `${inputId}-menu`;
const fieldName = select.name || select.dataset.connectedFilter || selectId;
const wasRequired = select.required;
const placeholderOption = Array.from(select.options).find((option) => option.value === "");
const wrapper = document.createElement("div");
const input = document.createElement("input");
const toggle = document.createElement("button");
const menu = document.createElement("div");
let activeIndex = -1;
select.id = selectId;
select.dataset.typeaheadEnhanced = "true";
select.required = false;
select.tabIndex = -1;
select.setAttribute("aria-hidden", "true");
select.classList.add("modal-typeahead-source");
wrapper.className = "modal-typeahead";
wrapper.dataset.typeaheadField = fieldName;
input.className = `form-control modal-typeahead-input${select.classList.contains("form-select-sm") ? " form-control-sm" : ""}`;
input.id = inputId;
input.type = "text";
input.autocomplete = "off";
input.value = select.value;
input.placeholder = placeholderOption?.textContent?.trim() || "Type to search";
input.required = wasRequired;
input.dataset.typeaheadInput = fieldName;
input.setAttribute("role", "combobox");
input.setAttribute("aria-autocomplete", "list");
input.setAttribute("aria-controls", menuId);
input.setAttribute("aria-expanded", "false");
toggle.className = "modal-typeahead-toggle";
toggle.type = "button";
toggle.setAttribute("aria-label", `Show options for ${fieldName}`);
toggle.innerHTML = ' ';
menu.className = "modal-typeahead-menu";
menu.id = menuId;
menu.setAttribute("role", "listbox");
const label = Array.from(root.querySelectorAll("label[for]")).find((item) => item.htmlFor === selectId);
if (label) {
label.htmlFor = inputId;
}
select.parentNode.insertBefore(wrapper, select);
wrapper.append(input, toggle, select, menu);
const refreshRelationshipOptions = () => {
const definition = getRelationshipFieldDefinition(fieldName);
if (!definition) return;
const selectedValue = select.value;
const placeholderText = placeholderOption?.textContent?.trim() || "Select record";
const labels = getRelationshipOptionLabels(fieldName);
const values = getEffectiveDatasourceRows(definition.dataKey)
.map((record) => String(record[definition.idKey] ?? ""))
.filter(Boolean);
const uniqueValues = [...new Set(selectedValue ? [selectedValue, ...values] : values)];
select.replaceChildren();
const placeholder = document.createElement("option");
placeholder.value = "";
placeholder.textContent = placeholderText;
select.append(placeholder);
uniqueValues.forEach((value) => {
const option = document.createElement("option");
option.value = value;
option.textContent = labels.get(value) || value;
select.append(option);
});
select.value = selectedValue;
};
const availableOptions = () => {
refreshRelationshipOptions();
return Array.from(select.options).filter((option) => option.value !== "");
};
const closeMenu = () => {
menu.classList.remove("show");
input.setAttribute("aria-expanded", "false");
activeIndex = -1;
};
const positionMenu = () => {
const rect = input.getBoundingClientRect();
const viewportHeight = globalThis.visualViewport?.height || window.innerHeight;
const viewportWidth = globalThis.visualViewport?.width || window.innerWidth;
const spaceBelow = viewportHeight - rect.bottom - 12;
const spaceAbove = rect.top - 12;
const openAbove = spaceBelow < 180 && spaceAbove > spaceBelow;
const availableHeight = Math.max(120, Math.min(288, (openAbove ? spaceAbove : spaceBelow) - 8));
menu.style.left = `${Math.max(8, Math.min(rect.left, viewportWidth - rect.width - 8))}px`;
menu.style.width = `${Math.min(rect.width, viewportWidth - 16)}px`;
menu.style.maxHeight = `${availableHeight}px`;
menu.style.top = openAbove
? `${Math.max(8, rect.top - Math.min(menu.scrollHeight || availableHeight, availableHeight) - 6)}px`
: `${Math.min(viewportHeight - availableHeight - 8, rect.bottom + 6)}px`;
};
const validateSelection = () => {
const valid = !input.value || input.value === select.value;
input.setCustomValidity(valid ? "" : "Choose an option from the list.");
};
const chooseOption = (option) => {
select.value = option.value;
input.value = option.value;
input.setCustomValidity("");
select.dispatchEvent(new Event("input", { bubbles: true }));
select.dispatchEvent(new Event("change", { bubbles: true }));
closeMenu();
input.focus();
};
const setActiveOption = (nextIndex) => {
const options = Array.from(menu.querySelectorAll("[data-typeahead-option]"));
if (!options.length) {
activeIndex = -1;
return;
}
activeIndex = (nextIndex + options.length) % options.length;
options.forEach((option, optionIndex) => option.classList.toggle("active", optionIndex === activeIndex));
options[activeIndex].scrollIntoView({ block: "nearest" });
};
const renderOptions = (searchTerm = "") => {
const normalizedTerm = searchTerm.trim().toLowerCase();
const matches = availableOptions().filter((option) => {
const haystack = `${option.value} ${option.textContent}`.toLowerCase();
return !normalizedTerm || haystack.includes(normalizedTerm);
});
menu.replaceChildren();
matches.slice(0, 50).forEach((option) => {
const button = document.createElement("button");
button.className = "modal-typeahead-option";
button.type = "button";
button.dataset.typeaheadOption = fieldName;
button.dataset.value = option.value;
button.setAttribute("role", "option");
button.setAttribute("aria-selected", String(option.value === select.value));
button.textContent = option.textContent;
button.addEventListener("mousedown", (event) => event.preventDefault());
button.addEventListener("click", () => chooseOption(option));
menu.append(button);
});
if (!matches.length) {
const empty = document.createElement("div");
empty.className = "modal-typeahead-empty";
empty.textContent = "No matching records";
menu.append(empty);
} else if (matches.length > 50) {
const remaining = document.createElement("div");
remaining.className = "modal-typeahead-empty";
remaining.textContent = `${matches.length - 50} more matches. Keep typing to narrow the list.`;
menu.append(remaining);
}
menu.classList.add("show");
input.setAttribute("aria-expanded", "true");
activeIndex = -1;
window.requestAnimationFrame(positionMenu);
};
const syncFromSelect = () => {
input.value = select.value;
input.setCustomValidity("");
};
select._syncTypeahead = syncFromSelect;
select.addEventListener("change", syncFromSelect);
input.addEventListener("focus", () => renderOptions(input.value === select.value ? "" : input.value));
input.addEventListener("input", () => {
if (input.value !== select.value) {
select.value = "";
}
validateSelection();
renderOptions(input.value);
});
input.addEventListener("keydown", (event) => {
const menuOptions = Array.from(menu.querySelectorAll("[data-typeahead-option]"));
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!menu.classList.contains("show")) {
renderOptions(input.value === select.value ? "" : input.value);
}
setActiveOption(activeIndex + (event.key === "ArrowDown" ? 1 : -1));
} else if (event.key === "Enter" && activeIndex >= 0 && menuOptions[activeIndex]) {
event.preventDefault();
menuOptions[activeIndex].click();
} else if (event.key === "Escape") {
closeMenu();
}
});
input.addEventListener("blur", () => {
window.setTimeout(() => {
closeMenu();
validateSelection();
}, 120);
});
toggle.addEventListener("click", () => {
if (menu.classList.contains("show")) {
closeMenu();
} else {
input.focus();
renderOptions("");
}
});
recordModalBody.addEventListener("scroll", () => {
if (menu.classList.contains("show")) {
window.requestAnimationFrame(positionMenu);
}
}, { passive: true });
});
}
function getFieldOptions(key, value) {
const normalizedKey = String(key).toLowerCase();
const currentValue = String(value ?? "");
const relationshipDefinition = getRelationshipFieldDefinition(normalizedKey);
const relationshipOptions = {
assignedprovider: () => getEffectiveDatasourceRows("providers").map((record) => record.name),
manager: () => [...new Set(getEffectiveDatasourceRows("cases").map((record) => record.manager))],
assignedowner: () => [...new Set(getEffectiveDatasourceRows("cases").map((record) => record.manager))]
};
if (relationshipDefinition) {
const options = getEffectiveDatasourceRows(relationshipDefinition.dataKey)
.map((record) => record[relationshipDefinition.idKey])
.filter((option) => option !== undefined && option !== "");
if (options.length) return ensureCurrentValue([...new Set(options)], currentValue);
}
if (relationshipOptions[normalizedKey]) {
const options = relationshipOptions[normalizedKey]().filter((option) => option !== undefined && option !== "");
if (options.length) {
return ensureCurrentValue(options, currentValue);
}
}
if (["city", "municipality", "county", "state"].includes(normalizedKey)) {
const providerValues = getEffectiveDatasourceRows("providers")
.map((record) => record[normalizedKey === "municipality" ? "municipality" : normalizedKey])
.filter((option) => option !== undefined && option !== "");
if (providerValues.length) {
return ensureCurrentValue([...new Set(providerValues)], currentValue);
}
}
const optionMap = {
priority: ["Critical", "High", "Medium", "Low"],
status: ["Submitted", "Under Review", "Matching", "Assigned", "Checked In", "Completed", "Open", "Awaiting response", "On track", "Needs review", "Escalated", "Available", "Near Capacity", "Waitlist"],
type: ["Emergency Hotel", "Medical Travel", "Transitional Housing", "Hotel", "Apartment Partner", "Transitional Housing", "Shelter Partner"],
accessible: ["Yes", "Partial", "No"],
shuttleSupport: ["Yes", "No"],
mealSupport: ["Yes", "No"],
transportationNeeded: ["true", "false"],
extensionRequested: ["true", "false"],
branchOfService: ["Army", "Navy", "Air Force", "Marine Corps", "Coast Guard", "Space Force"],
accessibilityNeeds: ["Wheelchair access", "Service animal support", "Ground-floor room", "No special need"],
phase: ["Medical Verification", "Funding Approval", "Provider Confirmation", "Check-In Coordination", "Extension Review", "Case Closure"],
fundingSource: ["VA referral", "Grant", "Nonprofit voucher", "County Program"],
domain: ["Privacy notice", "Identity proofing", "Work item routing", "Access management", "Audit monitoring", "Minimum necessary", "Retention", "Training", "External data sources", "Provider inquiries", "Consent and redress", "Cloud governance"],
reviewCadence: ["Weekly", "Monthly", "Quarterly"],
owner: ["Privacy Operations", "Care Operations", "Case Review Lead", "Security Operations", "ISSO", "Support Services", "Program Analytics", "Training Lead", "Integration Team", "Provider Success", "Platform Governance"]
,currenthousing: ["Unsheltered", "Emergency Shelter", "Hotel Placement", "Transitional Housing", "At Risk of Homelessness"]
,eligibilitystatus: ["Verified", "Pending Documentation", "Presumptively Eligible", "Review Required"]
,coordinatedentrystatus: ["Assessment Complete", "Prioritized", "Referral Pending", "Enrolled", "Needs Reassessment"]
,duplicatestatus: ["No duplicate found", "Potential duplicate", "Resolved duplicate"]
,assessmenttype: ["Housing Crisis", "Update", "Diversion", "Annual Reassessment"]
,programeligibility: ["HUD-VASH eligible", "SSVF eligible", "HCHV eligible", "Multiple programs", "Pending verification"]
,finalpriority: ["Critical", "High", "Medium", "Low"]
,overridestatus: ["No override", "Pending supervisor review", "Approved override", "Declined override"]
,referraldecision: ["Refer now", "Place on by-name list", "Diversion follow-up", "Eligibility review", "Reassess in 30 days"]
,signaturemethod: ["Electronic signature", "Written signature", "Witnessed verbal consent"]
,signaturestatus: ["Captured", "Pending", "Declined"]
,revocationstatus: ["Not revoked", "Revoked"]
,unittype: ["Hotel room", "Accessible hotel room", "Shelter bed", "Family unit", "Transitional apartment", "Medical respite bed"]
,accessibility: ["Standard", "Ground floor", "Wheelchair accessible", "Hearing accessible", "Service animal ready"]
,conflictstatus: ["Clear", "Review competing hold", "Conflict resolved"]
,worktype: ["Provider Response", "SLA Task", "Event Notification", "Extension & Transition", "Exception Resolution"]
,actionoutcome: ["Pending", "Accepted", "Declined", "Assigned", "In progress", "Completed", "Delivered", "Failed", "Retry scheduled", "Pending review", "Approved", "Transition scheduled", "Open", "Workaround identified", "Resolved"]
,communicationchannel: ["SMS", "Email", "Phone", "Secure message"]
,deliverystatus: ["Not applicable", "Delivered", "Pending", "Failed", "Retry scheduled"]
,nextaction: ["Contact provider", "Confirm veteran preference", "Escalate to supervisor", "Retry accessible channel", "Review funding", "Schedule transition conference", "Document resolution"]
,sourcesystem: ["Hosted baseline", "Profile-local workspace", "Partner system", "Authoritative service", "Manual verification"]
,verificationstatus: ["Unverified simulation", "Pending verification", "Verified", "Disputed", "Expired"]
,syncstatus: ["Published baseline", "Local only", "Queued", "Submitted", "Accepted", "Conflict", "Rejected"]
};
const matchedKey = Object.keys(optionMap).find((mapKey) => mapKey === normalizedKey);
if (matchedKey) {
return ensureCurrentValue(optionMap[matchedKey], currentValue);
}
if (typeof value === "boolean") {
return [String(value), String(!value)];
}
if (currentValue === "true" || currentValue === "false") {
return ["true", "false"];
}
if (normalizedKey.includes("status")) {
return ensureCurrentValue(["Submitted", "Under Review", "Matching", "Assigned", "Checked In", "Completed", "On track", "Needs review", "Escalated", "Available", "Near Capacity", "Waitlist", "Active", "Monitored", "Scheduled"], currentValue);
}
if (normalizedKey.includes("priority")) {
return ensureCurrentValue(["Critical", "High", "Medium", "Low"], currentValue);
}
return [];
}
function renderLinkedRecordActions(record) {
const links = [];
const requestId = record.requestId || (String(record.id || "").startsWith("REQ-") ? record.id : "");
const caseId = record.caseId || (String(record.id || "").startsWith("CASE-") ? record.id : "");
const providerId = record.providerId || (String(record.id || "").startsWith("PROV-") ? record.id : "");
const veteranId = record.veteranId || (String(record.id || "").startsWith("VET-") ? record.id : "");
if (record.customerReferenceNo) {
links.push({ label: "Customer journey", page: "requests", table: "requestTable", key: "customerReferenceNo", value: record.customerReferenceNo });
}
if (requestId) {
links.push({ label: "Veteran request", page: "requests", table: "requestTable", key: "id", value: requestId });
}
if (caseId) {
links.push({ label: "Case record", page: "cases", table: "caseTable", key: "caseId", value: caseId });
}
if (providerId) {
links.push({ label: "Provider record", page: "providers", table: "providerTable", key: "providerId", value: providerId });
}
if (veteranId) {
links.push({ label: "Veteran 360", page: "veterans", table: "veteranTable", key: "veteranId", value: veteranId });
links.push({ label: "Coordinated entry", page: "coordinatedEntry", table: "assessmentTable", key: "veteranId", value: veteranId });
links.push({ label: "Consent history", page: "consent", table: "consentTable", key: "veteranId", value: veteranId });
links.push({ label: "Agent operations", page: "partnerOperations", table: "partnerOperationsTable", key: "veteranId", value: veteranId });
}
if (!links.length) {
return "";
}
return `
Connected datasource
Open records that share this workflow reference.
${links.map((link) => `${escapeHtml(link.label)} `).join("")}
`;
}
function bindLinkedDatasourceFields(root) {
if (!root) {
return;
}
const savedContext = readVeteranContext();
if (savedContext && modalState?.mode === "table-create") {
root.querySelectorAll("[data-editable-record-form]").forEach((form) => applyLinkedContext(form, savedContext));
}
if (savedContext) {
const workflowForms = root.matches?.("[data-linked-workflow-form]") ? [root] : root.querySelectorAll("[data-linked-workflow-form]");
workflowForms.forEach((form) => applyLinkedContext(form, savedContext, { emptyOnly: true }));
}
root.querySelectorAll("[name='customerReferenceNo'], [name='requestId'], [name='caseId'], [name='providerId'], [name='veteranId']").forEach((field) => {
field.addEventListener("change", () => {
const form = field.closest("form");
const isPrimaryRecordEdit = form?.matches("[data-editable-record-form]") && modalState?.mode === "table-edit";
const isConnectedRecordEdit = form?.matches("[data-connected-record-form]");
if (isPrimaryRecordEdit || isConnectedRecordEdit) {
return;
}
const context = resolveLinkedContext(field.name, field.value);
if (context) {
persistVeteranContext(context);
const targets = root.matches?.("[data-linked-workflow-form]")
? document.querySelectorAll("[data-linked-workflow-form]")
: [root];
targets.forEach((target) => applyLinkedContext(target, context));
showToast("Linked data applied", "Related request, case, provider, and customer references were synchronized.", "info");
}
});
});
}
function readVeteranContext() {
if (!activeProfile) {
return null;
}
return storageService.readProfile(activeProfile.profileId, "linked-veteran-context", null);
}
function persistVeteranContext(context) {
if (!activeProfile || !context || !(context.veteran || context.veteranName || context.veteranId)) {
return;
}
storageService.writeProfile(activeProfile.profileId, "linked-veteran-context", {
...context,
savedAt: new Date().toISOString()
});
}
function buildVeteranContextFromRecord(record) {
if (!record) {
return null;
}
const veteranName = record.veteranName || record.veteran || record.requestorName || "";
return {
customerReferenceNo: record.customerReferenceNo || "",
veteranId: record.veteranId || "",
householdId: record.householdId || "",
requestId: record.requestId || record.id || "",
caseId: record.caseId || "",
providerId: record.providerId || "",
veteran: veteranName,
veteranName,
requestorName: veteranName,
provider: record.provider || record.providerName || "",
assignedProvider: record.assignedProvider || record.provider || record.providerName || "",
location: record.location || record.requestedCity || "",
requestedCity: record.requestedCity || record.location || ""
};
}
function resolveLinkedContext(fieldName, value) {
const requests = getEffectiveDatasourceRows("requests");
const cases = getEffectiveDatasourceRows("cases");
const providers = getEffectiveDatasourceRows("providers");
const veterans = getEffectiveDatasourceRows("veterans");
let request = null;
let caseRecord = null;
let provider = null;
let veteranProfile = null;
if (fieldName === "requestId") {
request = requests.find((record) => record.id === value);
} else if (fieldName === "caseId") {
caseRecord = cases.find((record) => record.caseId === value);
} else if (fieldName === "providerId") {
provider = providers.find((record) => record.providerId === value);
} else if (fieldName === "customerReferenceNo") {
request = requests.find((record) => record.customerReferenceNo === value);
} else if (fieldName === "veteranId") {
veteranProfile = veterans.find((record) => record.veteranId === value);
}
if (veteranProfile) {
request = requests.find((record) => record.id === veteranProfile.requestId) || request;
provider = providers.find((record) => record.providerId === veteranProfile.responsibleProviderId) || provider;
}
if (caseRecord && !request) {
request = requests.find((record) => record.id === caseRecord.requestId);
}
if (request && !caseRecord) {
caseRecord = cases.find((record) => record.requestId === request.id);
}
if (!veteranProfile) {
veteranProfile = veterans.find((record) => request?.id && record.requestId === request.id)
|| veterans.find((record) => request?.customerReferenceNo && record.customerReferenceNo === request.customerReferenceNo)
|| veterans.find((record) => caseRecord?.requestId && record.requestId === caseRecord.requestId)
|| veterans.find((record) => {
const linkedName = request?.veteran || caseRecord?.veteran || "";
return linkedName && record.veteranName === linkedName;
});
}
if (!provider) {
const providerId = caseRecord?.providerId || request?.providerId;
provider = providers.find((record) => record.providerId === providerId);
}
if (!request && !caseRecord && !provider && !veteranProfile) {
return null;
}
return {
customerReferenceNo: request?.customerReferenceNo || caseRecord?.customerReferenceNo || "",
veteranId: veteranProfile?.veteranId || "",
householdId: veteranProfile?.householdId || "",
requestId: request?.id || caseRecord?.requestId || "",
caseId: caseRecord?.caseId || request?.caseId || "",
providerId: provider?.providerId || caseRecord?.providerId || request?.providerId || "",
veteran: request?.veteran || caseRecord?.veteran || "",
veteranName: veteranProfile?.veteranName || request?.veteran || caseRecord?.veteran || "",
requestorName: request?.veteran || caseRecord?.veteran || "",
provider: provider?.name || caseRecord?.provider || "",
assignedProvider: provider?.name || caseRecord?.provider || "",
location: request?.location || caseRecord?.location || provider?.city || "",
requestedCity: request?.location || caseRecord?.location || provider?.city || ""
};
}
function applyLinkedContext(root, context, options = {}) {
Object.entries(context).forEach(([name, value]) => {
root.querySelectorAll(`[name='${name}']`).forEach((field) => {
if (options.emptyOnly && String(field.value || "").trim()) {
return;
}
if (value && Array.from(field.options || []).length && !Array.from(field.options).some((option) => option.value === String(value))) {
return;
}
if (value) {
field.value = value;
field._syncTypeahead?.();
}
});
});
}
function ensureCurrentValue(options, currentValue) {
const values = [...options];
if (currentValue && !values.some((option) => normalizeOptionValue(option) === normalizeOptionValue(currentValue))) {
values.unshift(currentValue);
}
return values;
}
function normalizeOptionValue(value) {
return String(value).trim().toLowerCase();
}
function compareValues(left, right, direction) {
const leftValue = normalizeSortValue(left);
const rightValue = normalizeSortValue(right);
if (leftValue < rightValue) {
return direction === "ascending" ? -1 : 1;
}
if (leftValue > rightValue) {
return direction === "ascending" ? 1 : -1;
}
return 0;
}
function parseCurrency(value) {
return Number(String(value ?? "").replace(/[$,% ,]/g, "")) || 0;
}
function parseNumeric(value) {
return Number(String(value ?? "").replace(/[, ]/g, "")) || 0;
}
function formatCurrency(value) {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0
}).format(Number(value || 0));
}
function formatInteger(value) {
return new Intl.NumberFormat("en-US", {
maximumFractionDigits: 0
}).format(Number(value || 0));
}
function normalizeSortValue(value) {
if (typeof value === "number") {
return value;
}
const numericValue = Number(String(value).replace(/[$,% ,]/g, ""));
if (!Number.isNaN(numericValue) && String(value).trim() !== "") {
return numericValue;
}
return String(value ?? "").toLowerCase();
}
function getSortIconClass(direction) {
if (direction === "ascending") {
return "bi bi-sort-down-alt sort-icon";
}
if (direction === "descending") {
return "bi bi-sort-down sort-icon";
}
return "bi bi-arrow-down-up sort-icon";
}
function slugify(value) {
return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
}
function metricCard(icon, label, value, note) {
return `
${escapeHtml(label)}
${escapeHtml(value)}
${escapeHtml(note)}
`;
}
function metricLinkCard(icon, label, value, note, pageKey, tableId, filterKey, filterValues) {
return `
${escapeHtml(label)}
${escapeHtml(value)}
${escapeHtml(note)}
`;
}
function storyCard(icon, title, text) {
return `
${escapeHtml(title)}
${escapeHtml(text)}
`;
}
function timelineCard(title, text) {
return `
Workflow step
${escapeHtml(title)}
`;
}
function insightCard(label, value, note) {
return `
${escapeHtml(label)}
${escapeHtml(value)}
${escapeHtml(note)}
`;
}
function renderContractDocumentAccordionItem(document, index) {
const itemId = `contract-doc-${index}`;
const sourceButton = document.sourceHtmlUrl
? `Open hosted source `
: "";
return `
${escapeHtml(document.summary)}
${sourceButton}
${escapeHtml(document.sourceMarkdown)}
${document.htmlContent}
`;
}
function dateTimeFormatter(value) {
const timestamp = Date.parse(value);
if (!Number.isFinite(timestamp)) {
return escapeHtml(String(value || "Not recorded"));
}
return escapeHtml(dateTimeDisplayFormatter.format(new Date(timestamp)));
}
function priorityPill(value) {
return `${escapeHtml(String(value))} `;
}
function statusPill(value) {
const tone = String(value).toLowerCase().includes("critical") ? "critical"
: String(value).toLowerCase().includes("high") ? "high"
: String(value).toLowerCase().includes("wait") ? "high"
: String(value).toLowerCase().includes("review") ? "medium"
: String(value).toLowerCase().includes("matching") ? "medium"
: String(value).toLowerCase().includes("escalated") ? "critical"
: "low";
return `${escapeHtml(String(value))} `;
}
function averageNumber(rows, key) {
const total = rows.reduce((sum, row) => sum + Number(row[key] || 0), 0);
return `${(total / Math.max(rows.length, 1)).toFixed(1)} hrs`;
}
function dominantValue(rows, key) {
const counts = rows.reduce((map, row) => {
const value = String(row[key]);
map[value] = (map[value] || 0) + 1;
return map;
}, {});
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
}
function escapeHtml(value) {
return value
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
})();