Files
shopdb-flask/frontend/src/utils/siteSettings.js
cproudlock 534f179ee6 Make main the lean product a site receives
main was 16 days and 259 commits behind the line the product is actually built
on, at contract 0.30.0 against 0.35.0, with no per-PC credential code at all. It
was neither current nor curated - just stale. This brings it forward and, at the
same time, makes it mean something: main is what a receiving site installs, and
nothing else.

WHAT IT CARRIES. Twelve plugins - backups, computers, endpoints, guides,
knowledgebase, machines, network, notifications, printers, slides, tools,
warranty - plus applications, which is manifest-less core and always ships. The
only manifest dependency inside that set is endpoints on computers, and both are
in it, so the closure is self-contained.

WHAT IT DOES NOT. employees, geenforce, measuringtools, printedparts and usb
stay on the site line. So do the Windows installer tree, the VM rehearsal
helpers, the agent tooling config, one site's data loader, the internal audit
and findings records, and the planner spreadsheet. 1,135 tracked files against
1,438.

A REMOVAL THAT BREAKS THE APP IS NOT A REMOVAL, and two nearly shipped:

deploy/site-profile-universal.json still named all seventeen plugins. It is the
file docs/DEPLOY.md tells a site to provision from, so a fresh install would
have failed at `flask plugin apply-profile` with PluginError - the first thing a
receiving site does, broken by the branch meant to serve them. It now names the
twelve that exist, and its comment says the two must agree.

agent/ was never refreshed. Whoever populated this branch copied shopdb/,
plugins/, frontend/ and tests/ from the site line and left the agent tree at its
September state: 22 C# and PowerShell sources missing, including AgentCredentials,
EnrollmentService, AgentHttpFactory and the fleet-alert client, plus one file the
site line had deleted still present. The old tree is internally consistent, so it
compiles, and nothing in CI builds it - every gate was green over a server that
speaks enrollment and per-PC credentials to a bundled agent source that cannot.
Resynced whole.

DECISIONS THIS ENCODES, rather than defers:

- The plugin-authoring lab builds printedparts, whose manifest depends on
  employees, so it could not stay. The lab remains on the site line and main
  ships no build-along tutorial. That is a real loss for an adopting developer
  and is recorded here rather than discovered later.
- Recognition, Training and Recertification notifications are no longer seeded.
  Each splits one notification into a card per employee and renders a photo,
  which needs a plugin this branch does not bundle. Seeding them would offer an
  author a type that cannot resolve anybody. A site that installs employees gets
  them from that plugin's own seed.
- Windows/IIS is documented as the legacy path throughout, and the README leads
  with Docker, because that is what a receiving site gets.

The API description is regenerated for THIS branch - 347 paths and 483
operations, down from 415 and 573 - so the published contract describes what is
here rather than what the site line serves. docs/CONFIG.md lost the two
measuring-tool label keys the code no longer declares, which two lanes had
decided opposite ways.

Suite: 3124 passed, 6 skipped. Naming and style gates pass. The docs gates run
rather than skip, and every index line count is derived from the file it names.
2026-09-19 11:24:40 -04:00

222 lines
9.0 KiB
JavaScript

// Shared read-through for public site settings (site_base_url, facility_name).
// The settings GET is public (jwt optional), so the kiosk dashboard and the
// print views can read these without auth. Fetched once and cached per page.
import { settingsApi } from '@/api'
import { withBase } from '@/utils/basePath'
let settingsCache = null
let inFlight = null
let retryAfter = 0
// Whether the last resolved load actually produced settings. A caller cannot
// tell that from the value alone: a failed load and a site that simply has not
// configured a key both read as empty, and those want opposite handling -
// hide the feature vs try again.
export function settingsLoadFailed() {
return settingsCache === null
}
// A failed load is cached briefly, not for the page session. A transient blip
// used to blank every settings-driven link until the operator reloaded, and
// they have no reason to know that would fix it. A short window still bounds a
// hard-down backend to two requests a minute per client.
const FAILURE_RETRY_MS = 30000
// The in-flight promise is cached alongside the result. Callers that arrive
// during the first load share one request instead of each firing their own;
// applyBranding() alone awaits five settings in sequence at bootstrap.
async function loadSettings() {
if (settingsCache) return settingsCache
if (inFlight) return inFlight
if (retryAfter && Date.now() < retryAfter) return {}
inFlight = settingsApi.list()
.then((response) => {
const items = response.data?.data || response.data || []
const loaded = {}
for (const s of items) loaded[s.key] = s.value
settingsCache = loaded
retryAfter = 0
return loaded
})
.catch((error) => {
console.error('Error loading site settings:', error)
retryAfter = Date.now() + FAILURE_RETRY_MS
return {}
})
.finally(() => { inFlight = null })
return inFlight
}
export async function getSetting(key, fallback = '') {
const settings = await loadSettings()
const value = settings[key]
return (value === undefined || value === null || value === '') ? fallback : value
}
// Public base URL for QR codes / absolute links. Falls back to the current
// browsing origin when a site has not set one.
export async function getSiteBaseUrl() {
return getSetting('site_base_url', window.location.origin)
}
// Facility name shown on the shopfloor dashboard.
export async function getFacilityName() {
return getSetting('facility_name', 'ShopDB')
}
// Environment channel label (e.g. 'DEV') injected by the backend from
// SHOPDB_ENV_LABEL. Empty on stable/main deployments, which renders no badge.
// Drives the red DEV tag in the sidebar so a bleeding-edge container is
// obviously distinct from a stable one running side by side.
export async function getEnvLabel() {
return getSetting('env_label', '')
}
// Main site logo (sidebar, login, dashboard header). Fallback = shipped GE mark.
export async function getSiteLogo() {
return withBase(await getSetting('site_logo', '/ge-aerospace-logo.svg'))
}
// Logo composited into the center of printer QR codes. Empty = no overlay.
// Note: '' is a valid "no overlay" value, so read the raw setting rather than
// getSetting (which swaps '' for the fallback).
export async function getQrLogo() {
const settings = await loadSettings()
const value = settings['qr_logo']
return withBase((value === undefined || value === null) ? '/ge-monogram.svg' : value)
}
// Logo printed on machine inspection badges.
export async function getBadgeLogo() {
return withBase(await getSetting('badge_logo', '/ge-aerospace-logo.svg'))
}
// Browser-tab favicon. Empty = keep the shipped /favicon.svg.
export async function getFavicon() {
const value = await getSetting('site_favicon', '')
return value ? withBase(value) : value
}
// Brand primary color override. Empty = built-in palette from style.css.
export async function getBrandPrimaryColor() {
return getSetting('brand_primary_color', '')
}
// Primary hover/active color (--primary-dark). Empty = derive from primary.
export async function getBrandPrimaryDarkColor() {
return getSetting('brand_primary_dark_color', '')
}
// Accent color (--secondary). Empty = built-in palette from style.css.
export async function getBrandAccentColor() {
return getSetting('brand_accent_color', '')
}
// Sidebar background color (--sidebar-bg). Empty = built-in palette.
export async function getBrandSidebarColor() {
return getSetting('brand_sidebar_color', '')
}
// Darken a #rrggbb hex color by the given fraction (0.15 = 15% darker).
// Returns null for anything that is not a 6-digit hex so callers can skip it.
function darkenHexColor(hex, fraction) {
const match = /^#([0-9a-fA-F]{6})$/.exec(hex)
if (!match) return null
const num = parseInt(match[1], 16)
const scale = 1 - fraction
const red = Math.round(((num >> 16) & 0xff) * scale)
const green = Math.round(((num >> 8) & 0xff) * scale)
const blue = Math.round((num & 0xff) * scale)
const toHex = (channel) => channel.toString(16).padStart(2, '0')
return `#${toHex(red)}${toHex(green)}${toHex(blue)}`
}
// ServiceNow ticket-link config. Returns the enabled flag, incident/change URL
// templates, and the global-search URL template (all with a {ticket}
// placeholder).
//
// The defaults are BLANK and the integration ships OFF, matching the server.
// They used to be one organisation's QA ServiceNow tenant, so any site that had
// not configured ServiceNow still rendered ticket links - pointing its
// technicians at a tenant they cannot reach and, for an adopting site, at
// somebody else's. A blank URL renders tickets as plain text, which is the
// correct behaviour for "not configured".
export async function getServicenowUrls() {
const enabledRaw = await getSetting('servicenow_enabled', 'false')
const enabled = enabledRaw !== 'false' && enabledRaw !== '0' && enabledRaw !== false
const incidentUrl = await getSetting('servicenow_incident_url', '')
const changeUrl = await getSetting('servicenow_change_url', '')
const searchUrl = await getSetting('servicenow_search_url', '')
return { enabled, incidentUrl, changeUrl, searchUrl }
}
// Deep links into the Azure portal for a device ShopDB knows the Entra ids of.
//
// Both are TEMPLATES held in settings rather than built here, because the host
// is a tenant fact: this site is on the US Government cloud (portal.azure.us)
// and the commercial cloud is portal.azure.com. Microsoft also moves these
// blade paths from time to time, and a site can fix that itself by editing a
// setting instead of waiting for a release.
//
// Empty is the default and means "no link" - the id still renders as text.
//
// `loaded` distinguishes a real answer from a failed fetch. Both return empty
// strings, but only one of them means "this site has no portal links".
export async function getEntraDeviceUrls() {
const entraUrl = await getSetting('entra_device_url', '')
const intuneUrl = await getSetting('intune_device_url', '')
const lapsUrl = await getSetting('laps_device_url', '')
return { entraUrl, intuneUrl, lapsUrl, loaded: !settingsLoadFailed() }
}
// Printer hostname template. {ip} is replaced with the dash-separated IP.
export async function getPrinterHostnameTemplate() {
return getSetting('printer_hostname_template', 'Printer-{ip}.printer.geaerospace.net') // ADR-015-OK: GE Aerospace-wide domain, and only the DEFAULT of a documented setting every site can override.
}
// Email domain appended to a contact SSO to build email/Teams links
// (sso@domain). Unset falls back to geaerospace.com; an explicit blank value
// means "disable contact action buttons", so read the raw setting rather than
// getSetting (which swaps '' for the fallback).
export async function getContactEmailDomain() {
const settings = await loadSettings()
const value = settings['contact_email_domain']
return (value === undefined || value === null) ? 'geaerospace.com' : value
}
// Apply per-site favicon + brand color at bootstrap. Empty settings keep the
// shipped defaults. Do not touch the style.css palette here.
export async function applyBranding() {
const favicon = await getFavicon()
if (favicon) {
let link = document.querySelector('link[rel="icon"]')
if (!link) {
link = document.createElement('link')
link.rel = 'icon'
document.head.appendChild(link)
}
link.href = favicon
}
const rootStyle = document.documentElement.style
const primaryColor = await getBrandPrimaryColor()
if (primaryColor) {
rootStyle.setProperty('--primary', primaryColor)
}
// Hover color: use the explicit value, else darken primary ~15%.
const primaryDarkColor = await getBrandPrimaryDarkColor()
if (primaryDarkColor) {
rootStyle.setProperty('--primary-dark', primaryDarkColor)
} else if (primaryColor) {
const derived = darkenHexColor(primaryColor, 0.15)
if (derived) rootStyle.setProperty('--primary-dark', derived)
}
const accentColor = await getBrandAccentColor()
if (accentColor) {
rootStyle.setProperty('--secondary', accentColor)
}
const sidebarColor = await getBrandSidebarColor()
if (sidebarColor) {
rootStyle.setProperty('--sidebar-bg', sidebarColor)
}
}