SNAD / Business Central - BLISS - Basic Line ID for Swift Scanning

// ==UserScript==
// @name         Business Central - BLISS - Basic Line ID for Swift Scanning
// @namespace    https://allmar.com/business_systems
// @version      0.20
// @description  Basic Line ID for Swift Scanning
// @author       SNAD
// @match        https://businesscentral.dynamics.com/*
// @match        https://*.businesscentral.dynamics.com/*
// @updateURL    https://openuserjs.org/meta/SNAD/Business_Central_-_BLISS_-_Basic_Line_ID_for_Swift_Scanning.meta.js
// @downloadURL  https://openuserjs.org/install/SNAD/Business_Central_-_BLISS_-_Basic_Line_ID_for_Swift_Scanning.user.js
// @copyright    2026, SNAD (https://openuserjs.org/users/SNAD)
// @license      GPL-3.0-or-later
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';

    // Native BC line styling BLISS reacts to. Attention -> red, Ambiguous -> yellow.
    // These are real CSS classes BC applies to the styled element, so detection is a
    // plain class check, same mechanism for both.
    const ATTENTION_SELECTOR = '.ms-nav-attention-styleview, [class*="style-attention"]';
    const AMBIGUOUS_SELECTOR = '.ms-nav-ambiguous-styleview, [class*="style-ambiguous"]';
    const NATIVE_SELECTORS = [
        '.ms-nav-attention-styleview', '[class*="style-attention"]',
        '.ms-nav-ambiguous-styleview', '[class*="style-ambiguous"]',
    ];
    // Links and drill-downs in list columns: BC gives their value the theme's
    // brand color, and that color is the only thing that marks them as links until hovered.
    // Forcing the row's text color onto them made them look like plain text, so they keep it,
    // plus the dashed underline BC gives lookups in a selected or hovered row.
    const LINK_SELECTORS = ['[class*="thm-color--brand-primary"]'];

    // Contract / Material List pages additionally show an "Order Status Icon" and a
    // "Release Status Icon" column. Unlike Attention/Ambiguous, these carry no special
    // CSS class at all - BC renders them as literal colored emoji characters (e.g. "In
    // Process" = a blue circle/square glyph), so blue can only be detected by reading
    // the actual icon text, not by matching a class. Squares are used for Order Status,
    // circles for Release Status, but the glyph sets are checked together either way.
    const ICON_TOKENS = {
        red: ['🟥', '🔴'],
        yellow: ['🟨', '🟡'],
        blue: ['🟦', '🔵'],
        black: ['⬛', '⚫'],
        // Green ("Approved" / "Favorable") isn't part of the priority rule below - it
        // carries no weight, same as a blank cell.
    };
    const ORDER_STATUS_ICON_HEADER = 'Order Status Icon';
    const RELEASE_STATUS_ICON_HEADER = 'Release Status Icon';

    // Lower number = more urgent, wins a head-to-head comparison.
    const SEVERITY = { yellow: 1, red: 2, blue: 3, black: 4 };

    const NONLIVE_CLASS = 'bliss-nonlive';
    const ENV_BUTTON_SELECTOR = '#BC_EnvironmentLauncher button[title]';

    // Which environment + company counts as "live" is stored in this browser, not in the
    // script, so auto-updates from OpenUserJS can't wipe it and the published script never
    // names anyone's company. On first run BLISS asks (one confirm popup) whether the
    // company you're in is your live one; blissMarkLive() / blissClearLive() in the
    // browser console set or reset it manually. The extension's toolbar button calls the
    // same functions, plus blissStatus(), so keep those three names.
    const LIVE_STORAGE_KEY = 'bliss.liveContext';
    const DECLINED_STORAGE_KEY = 'bliss.liveDeclined';

    const STYLE_ID = 'bliss-style';
    if (!document.getElementById(STYLE_ID)) {
        const style = document.createElement('style');
        style.id = STYLE_ID;
        const preserveNative = [...NATIVE_SELECTORS, ...LINK_SELECTORS].map(s => `:not(${s}):not(${s} *)`).join('');
        style.textContent = `
            :root {
                --bliss-normal-bg: #b2e9ec;
                --bliss-red-bg: #ecb2c0;
                --bliss-blue-bg: #b7c3f2;
                --bliss-yellow-bg: #f0e6a0;
                --bliss-normal-text: #000000;
                /* Fixed in both themes on purpose: the header's native text is white, so
                   the bar needs to stay dark for contrast regardless of light/dark mode. */
                --bliss-nonlive-bg: #901010;
                --bliss-nonlive-hover: #6b0c0c;
            }
            @media (prefers-color-scheme: dark) {
                :root {
                    --bliss-normal-bg: #0f3d42;
                    --bliss-red-bg: #42121d;
                    --bliss-blue-bg: #1c2b6e;
                    --bliss-yellow-bg: #4a3b08;
                    --bliss-normal-text: #e8e8e8;
                }
            }
            tr.bliss-row[data-bliss] { box-shadow: none !important; }
            tr.bliss-row[data-bliss="normal"] { --bliss-bg: var(--bliss-normal-bg); }
            tr.bliss-row[data-bliss="red"]    { --bliss-bg: var(--bliss-red-bg); }
            tr.bliss-row[data-bliss="blue"]   { --bliss-bg: var(--bliss-blue-bg); }
            tr.bliss-row[data-bliss="yellow"] { --bliss-bg: var(--bliss-yellow-bg); }

            tr.bliss-row[data-bliss],
            tr.bliss-row[data-bliss] td:not(.grid-selection-column),
            tr.bliss-row[data-bliss] td:not(.grid-selection-column) * {
                background-image: linear-gradient(var(--bliss-bg), var(--bliss-bg)) !important;
                background-color: var(--bliss-bg) !important;
                color-scheme: light !important;
            }
            tr.bliss-row[data-bliss] td.grid-selection-column {
                background: transparent !important;
                background-image: none !important;
            }
            /* One consistent text color across the row, except genuinely-flagged native
               attention/ambiguous elements and links (and their descendants), which keep
               BC's own color. Each :not() clause must stay on the same line as the selector it
               modifies - CSS treats whitespace between compound selectors as a descendant
               combinator. */
            tr.bliss-row[data-bliss],
            tr.bliss-row[data-bliss] td:not(.grid-selection-column),
            tr.bliss-row[data-bliss] td:not(.grid-selection-column) *${preserveNative} {
                color: var(--bliss-normal-text) !important;
            }
            /* Links get the same dashed underline BC draws under lookups (Item No., Location...)
               in a selected row and in the row under the mouse, so they read as clickable without
               pointing at them. Pointing at the link itself still shows BC's own solid underline. */
            ${LINK_SELECTORS.map(s => `tr.bliss-row[data-bliss] ${s}:not(:hover), ` +
                `tbody tr[role="row"]:hover ${s}:not(:hover)`).join(', ')} {
                text-decoration: underline dashed !important;
            }

            /* Non-live top bar. Background only - overriding text/icon color here reaches
               into the Links flyout menu (a DOM child of the header) and breaks it. */
            html.${NONLIVE_CLASS} #O365_NavHeader,
            html.${NONLIVE_CLASS} #O365_NavHeader .o365sx-button,
            html.${NONLIVE_CLASS} #O365_NavHeader .o365sx-appName,
            html.${NONLIVE_CLASS} #BC_EnvironmentLauncher button {
                background-color: var(--bliss-nonlive-bg) !important;
            }
            html.${NONLIVE_CLASS} #O365_NavHeader button.o365sx-button:hover,
            html.${NONLIVE_CLASS} #BC_EnvironmentLauncher button:hover {
                background-color: var(--bliss-nonlive-hover) !important;
            }
        `;
        (document.head || document.documentElement).appendChild(style);
    }

    // Caches each document's header-text -> column-index mapping, so looking up the
    // Order/Release Status Icon columns is O(1) after the first row. BC renders a grid's
    // header row and its body rows in two SEPARATE <table> elements (frozen/scrollable
    // column split) that share column ordering but aren't otherwise connected in the DOM
    // - row.closest('table') only finds the header-less body table, so the header has to
    // be located by searching every table's thead in the row's document instead.
    const headerIndexCache = new WeakMap();
    function getHeaderIndex(doc, headerText) {
        let map = headerIndexCache.get(doc);
        if (!map) {
            map = new Map();
            doc.querySelectorAll('table thead tr').forEach(headerRow => {
                headerRow.querySelectorAll('th, td').forEach((h, i) => {
                    const text = h.textContent.trim();
                    if (text && !map.has(text)) map.set(text, i);
                });
            });
            headerIndexCache.set(doc, map);
        }
        return map.get(headerText);
    }

    // A status-icon cell can render as a read-only span (textContent/title carry the
    // glyph) or, when the row is mid-edit, as an <input> (the glyph lives in .value).
    // Check every source so the currently-focused row still classifies correctly.
    function cellStatusText(cell) {
        if (!cell) return '';
        const input = cell.querySelector('input');
        const titled = cell.querySelector('[title]');
        return (cell.textContent || '') +
            (input ? input.value || '' : '') +
            (titled ? titled.getAttribute('title') || '' : '');
    }

    function tokenForIcon(text) {
        for (const [token, glyphs] of Object.entries(ICON_TOKENS)) {
            if (glyphs.some(g => text.includes(g))) return token;
        }
        return null; // green, blank, or unrecognized - contributes nothing
    }

    // Reproduces the full Order-Status x Release-Status priority table with 3 rules:
    // take the more urgent of the two (yellow > red > blue > black), except a Release of
    // black paired with a non-black Order is always flagged red (release says done, but
    // the order itself isn't - worth a second look), and a black result just means
    // everything's complete, so show no special highlight at all.
    function mergeContractStatus(orderToken, releaseToken) {
        if (releaseToken === 'black' && orderToken && orderToken !== 'black') {
            return 'red';
        }
        const candidates = [orderToken, releaseToken].filter(Boolean);
        if (candidates.length === 0) return null;
        let winner = candidates[0];
        for (const c of candidates) {
            if (SEVERITY[c] < SEVERITY[winner]) winner = c;
        }
        return winner === 'black' ? 'normal' : winner;
    }

    function classifyRow(row) {
        const orderIdx = getHeaderIndex(row.ownerDocument, ORDER_STATUS_ICON_HEADER);
        const releaseIdx = getHeaderIndex(row.ownerDocument, RELEASE_STATUS_ICON_HEADER);
        if (orderIdx !== undefined || releaseIdx !== undefined) {
            const cells = row.querySelectorAll('td');
            const orderToken = tokenForIcon(cellStatusText(cells[orderIdx]));
            const releaseToken = tokenForIcon(cellStatusText(cells[releaseIdx]));
            const merged = mergeContractStatus(orderToken, releaseToken);
            if (merged) return merged;
        }

        if (row.querySelector(ATTENTION_SELECTOR)) return 'red';
        if (row.querySelector(AMBIGUOUS_SELECTOR)) return 'yellow';
        return 'normal';
    }

    let lastSelectedRows = new Set();

    function forceBlueHighlights() {
        const currentlySelected = new Set();

        document.querySelectorAll('tbody tr[role="row"][aria-selected="true"]').forEach(row => {
            const rowKey = row.getAttribute('rowkey') || row.getAttribute('aria-rowindex') || 'unknown';
            currentlySelected.add(rowKey);
            row.classList.add('bliss-row');
            row.dataset.bliss = classifyRow(row);
        });

        // Cleanup deselected rows
        lastSelectedRows.forEach(oldKey => {
            if (!currentlySelected.has(oldKey)) {
                document.querySelectorAll('tr.bliss-row').forEach(row => {
                    const rowKey = row.getAttribute('rowkey') || row.getAttribute('aria-rowindex');
                    if (rowKey === oldKey) {
                        row.classList.remove('bliss-row');
                        delete row.dataset.bliss;
                    }
                });
            }
        });

        lastSelectedRows = currentlySelected;
    }

    // ---- Live environment/company (stored per browser) ----
    function loadLiveContext() {
        try {
            const raw = localStorage.getItem(LIVE_STORAGE_KEY);
            const parsed = raw ? JSON.parse(raw) : null;
            if (parsed && parsed.environment && parsed.company) return parsed;
        } catch (e) { /* storage blocked or corrupt - treat as not set */ }
        return null;
    }
    let liveContext = loadLiveContext();

    // The environment button's title reads "<Company>, Environment: <Env>". The header
    // only exists in the top-level document, so in BC's content iframes this returns null.
    function readCurrentContext() {
        const btn = document.querySelector(ENV_BUTTON_SELECTOR);
        if (!btn) return null;
        const title = btn.getAttribute('title');
        const marker = ', Environment: ';
        const idx = title.lastIndexOf(marker);
        if (idx === -1) return null;
        return {
            company: title.slice(0, idx).trim(),
            environment: title.slice(idx + marker.length).trim()
        };
    }

    function saveLiveContext(ctx) {
        try {
            localStorage.setItem(LIVE_STORAGE_KEY, JSON.stringify(ctx));
        } catch (e) {
            console.log('BLISS: could not save to browser storage (blocked?).', e);
            return false;
        }
        liveContext = ctx;
        console.log(`BLISS: live set to "${ctx.company}" in "${ctx.environment}". Every other company/environment now gets the red top bar.`);
        return true;
    }

    // Companies answered "Cancel" to in this tab, so the popup only asks once per company
    // per tab instead of on every page change. Session-scoped: a new tab asks again.
    function contextKey(ctx) { return `${ctx.environment}|${ctx.company}`; }
    function loadDeclined() {
        try { return new Set(JSON.parse(sessionStorage.getItem(DECLINED_STORAGE_KEY)) || []); }
        catch (e) { return new Set(); }
    }
    function addDeclined(ctx) {
        const set = loadDeclined();
        set.add(contextKey(ctx));
        try { sessionStorage.setItem(DECLINED_STORAGE_KEY, JSON.stringify([...set])); } catch (e) { /* ignore */ }
    }

    function askIfLive(ctx) {
        if (loadDeclined().has(contextKey(ctx))) return;
        const yes = window.confirm(
            `BLISS setup (one time):\n\nIs "${ctx.company}" in environment "${ctx.environment}" your LIVE company?\n\n` +
            'OK = yes. Every other company/environment will get a red top bar.\n' +
            "Cancel = no. You'll be asked again when you open a different company."
        );
        if (yes) saveLiveContext(ctx);
        else addDeclined(ctx);
    }

    function applyNonLiveTopBar() {
        const ctx = readCurrentContext();
        if (!ctx) return; // not enough info yet, leave the bar alone
        if (!liveContext) {
            // Not set up yet: leave the bar alone rather than flag the live company red,
            // and ask whether this company is the live one.
            document.documentElement.classList.remove(NONLIVE_CLASS);
            askIfLive(ctx);
            if (!liveContext) return;
        }
        const isLive = ctx.environment === liveContext.environment && ctx.company === liveContext.company;
        document.documentElement.classList.toggle(NONLIVE_CLASS, !isLive);
    }

    window.blissMarkLive = function () {
        const ctx = readCurrentContext();
        if (!ctx) {
            console.log('BLISS: environment button not found. Run this from the top frame of a BC page.');
            return;
        }
        if (saveLiveContext(ctx)) applyNonLiveTopBar();
    };

    // Clearing also forgets this tab's "Cancel" answers, so the setup popup comes back
    // straight away for the company you're on.
    window.blissClearLive = function () {
        try {
            localStorage.removeItem(LIVE_STORAGE_KEY);
            sessionStorage.removeItem(DECLINED_STORAGE_KEY);
        } catch (e) { /* ignore */ }
        liveContext = null;
        console.log('BLISS: live company cleared.');
        applyNonLiveTopBar();
    };

    // What the toolbar popup shows: the saved live company and the one this page is in
    // (null when not set / not readable yet).
    window.blissStatus = function () {
        return { live: liveContext, here: readCurrentContext() };
    };

    // Keep other open BC tabs in sync when the live company is set or cleared in one tab.
    window.addEventListener('storage', (e) => {
        if (e.key !== LIVE_STORAGE_KEY) return;
        liveContext = loadLiveContext();
        applyNonLiveTopBar();
    });
    // --------------------------------------------------------

    function updateAll() {
        forceBlueHighlights();
        applyNonLiveTopBar();
    }

    // Coalesce bursts of mutations into at most one update per animation frame, so a
    // page that's already busy (lots of mutations firing close together) doesn't also get
    // hit with a pile of synchronous re-renders stacking up on top of that.
    let rafScheduled = false;
    function scheduleUpdate() {
        if (rafScheduled) return;
        rafScheduled = true;
        requestAnimationFrame(() => {
            rafScheduled = false;
            updateAll();
        });
    }

    // One shared observer for both features. 'title' is watched so company/environment
    // switches (BC changes these without a full reload) are caught, but only a title
    // change on the environment button itself schedules work - BC sets titles on lots
    // of grid cells too.
    const observer = new MutationObserver((mutations) => {
        if (mutations.some(m =>
            m.attributeName === 'aria-selected' ||
            m.addedNodes.length ||
            (m.attributeName === 'title' && m.target.matches && m.target.matches(ENV_BUTTON_SELECTOR))
        )) {
            scheduleUpdate();
        }
    });

    function init() {
        observer.observe(document.documentElement, {
            childList: true,
            subtree: true,
            attributes: true,
            attributeFilter: ['aria-selected', 'class', 'title']
        });
        updateAll();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    window.addEventListener('popstate', updateAll);
    const originalPush = history.pushState;
    history.pushState = function (...args) {
        originalPush.apply(this, args);
        setTimeout(updateAll, 200);
    };

    console.log('BLISS ACTIVE: Selected lines now highlighted');
})();