// company-list.js — shared helper: fetch the LIVE SAP company list once, // cached for the page's lifetime. Backed by GET /api/companies (server // scans SQL Server for company databases, no hardcoded list — public/no-auth // since register.html/vendor-register.html use it before login too). // // Admin → user → "Displayed SAP Company" can restrict which of those // companies a given user sees: filtered HERE, client-side, against the // logged-in user's allowedCompanies (baked into portal_user at login/refresh // — see server.js buildAuthPayload). Empty/absent = no restriction (sees // everything the server found), same as unauthenticated pages. This is a // display-level filter only, matching how Issue Items/Man Power/OEE tab // restrictions work elsewhere in this app — it doesn't block API calls made // with an explicit company param. (function(){ let _p = null; window.fetchCompanyList = function(){ if(_p) return _p; _p = fetch('/api/companies').then(r=>r.json()).then(d=>{ const all=d.success?(d.data||[]):[]; let allowed=null; try{ const u=JSON.parse(sessionStorage.getItem('portal_user')||'null'); if(u&&Array.isArray(u.allowedCompanies)&&u.allowedCompanies.length) allowed=new Set(u.allowedCompanies.map(String)); }catch(_e){} return allowed?all.filter(c=>allowed.has(String(c.value))):all; }).catch(()=>[]); return _p; }; // Every page initializes its working company as `let _co=window.__DEFAULT_ // COMPANY__` (the .env SAP_B1_COMPANY, injected server-side into EVERY // page for EVERY user — see server.js's static-file middleware). That's // fine for an unrestricted user, but a user restricted to specific // companies (Admin → user → "Displayed SAP Company") would still silently // default to and fetch data from the .env company, even when it's NOT in // their allowed list — the restriction only ever filtered the DROPDOWN, // never the actual starting selection. Fixed here, synchronously, before // any page's own inline script runs (this file is always loaded in , // ahead of the page body): if the user has a non-empty allowedCompanies // list that does NOT include the .env default, swap window.__DEFAULT_ // COMPANY__ to their first allowed company so every page's `_co` picks up // the corrected value with no per-page changes needed. try{ const u=JSON.parse(sessionStorage.getItem('portal_user')||'null'); if(u&&Array.isArray(u.allowedCompanies)&&u.allowedCompanies.length&&!u.allowedCompanies.includes(window.__DEFAULT_COMPANY__)){ window.__DEFAULT_COMPANY__=u.allowedCompanies[0]; } }catch(_e){} })();