<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <label>Scheduler: Rate Card</label>
    <protected>false</protected>
    <values>
        <field>b3s__Configuration__c</field>
        <value xsi:type="xsd:string"><![CDATA[
        ]]></value>
    </values>
    <values>
        <field>b3s__Javascript_Code__c</field>
        <value xsi:type="xsd:string"><![CDATA[
async ({ event, events, contactId, loaders, matchingModifiers, EvaluationResult }) => {
    const results = [];
    if (!contactId) {
        console.warn('No contact id for evaluation');
        return results;
    }

    const cards = loaders.find((l) => l.name === 'rateCards')?.loader?.records || [];
    const itemsByCard = loaders.find((l) => l.name === 'rateCardItems')?.loader?.grouped || {};
    if (cards.length === 0) return results;

    const MS_HOUR = 3600000;
    // event.start / event.end are already shifted into the shift site's timezone by the scheduler,
    // so the browser-local getters on these Dates read the site's wall clock. Every band and
    // weekday comparison below therefore works in site-local time, as the pay/bill engine does.
    const segStart = new Date(event.start).getTime();
    const segEnd = new Date(event.end).getTime();
    if (isNaN(segStart) || isNaN(segEnd) || segEnd <= segStart) return results;

    // ---------------------------------------------------------------
    // Card selection, mirroring the pay/bill engine's rate card resolution
    // ---------------------------------------------------------------

    const asDay = (value) => (value ? new Date(String(value).split('T')[0]).getTime() : null);
    const shiftDay = asDay(new Date(segStart).toISOString());

    // A card is effective when it is active, opened on or before the shift day and has not closed.
    const isEffective = (card) => {
        if (card.b3s__Active__c === false) return false;
        const from = asDay(card.b3s__Valid_From__c);
        const to = asDay(card.b3s__Valid_To__c);
        if (from == null || from > shiftDay) return false;
        if (to == null) return true;
        if (to < from) return false;
        return to >= shiftDay;
    };

    // Ties: latest Valid_From wins, then most recently created.
    const isBetter = (card, best) => {
        const cardFrom = asDay(card.b3s__Valid_From__c);
        const bestFrom = asDay(best.b3s__Valid_From__c);
        if (cardFrom !== bestFrom) return cardFrom > bestFrom;
        return new Date(card.CreatedDate).getTime() > new Date(best.CreatedDate).getTime();
    };

    const record = event.extendedProps.record || {};

    // Job > Site > Account only. The pay/bill engine also walks ParentAccount and
    // CostCenter, but b3s__Work_Job__r.b3s__Account__r.ParentId and b3s__Cost_Center__c are not
    // on the scheduler's loaded shift fields. Add them to the definition's shift fieldsToLoad and
    // two more levels here if an org configures those hierarchy tokens.
    // Ordered most specific first; the index doubles as the specificity score.
    const CONTEXT_LEVELS = [
        ['b3s__Work_Job__c', record.b3s__Work_Job__c],
        ['b3s__Work_Site__c', record.b3s__Work_Site__c],
        ['b3s__Account__c', record.b3s__Work_Job__r?.b3s__Account__c]
    ];

    // Every context lookup a card populates has to match the shift, so a card scoped to another
    // job or site is discarded. The score is the most specific level the card names: 3 job,
    // 2 site, 1 account, 0 for a card that names none, which is a global fallback.
    // Returns -1 when the card names a context the shift does not match.
    const contextScore = (card) => {
        let score = 0;
        for (let i = 0; i < CONTEXT_LEVELS.length; i++) {
            const [field, shiftValue] = CONTEXT_LEVELS[i];
            if (card[field] == null) continue;
            if (card[field] !== shiftValue) return -1;
            score = Math.max(score, CONTEXT_LEVELS.length - i);
        }
        return score;
    };

    /**
     * Pick the card that applies to this shift.
     *
     * Candidate side: cards belonging to the worker, most specific context winning, falling back
     * to their global card. Shift side: cards belonging to nobody, which must name a context.
     * Within a specificity level the usual tie-break applies.
     */
    const selectCard = (forCandidate) => {
        let best = null;
        let bestScore = -1;
        for (const card of cards) {
            if (forCandidate ? card.b3s__Contact__c !== contactId : !!card.b3s__Contact__c) continue;
            if (!isEffective(card)) continue;
            const score = contextScore(card);
            if (score < 0) continue;
            if (!forCandidate && score === 0) continue;
            if (best == null || score > bestScore || (score === bestScore && isBetter(card, best))) {
                best = card;
                bestScore = score;
            }
        }
        return best == null ? null : { card: best, score: bestScore };
    };

    const candidateMatch = selectCard(true);
    // No candidate card that applies here means the shift's own card stands: nothing to flag.
    if (!candidateMatch) return results;
    const candidateCard = candidateMatch.card;

    const shiftMatch = selectCard(false);
    if (!shiftMatch) return results;
    const shiftCard = shiftMatch.card;

    // Rates are plain numbers with the ISO code carried alongside; comparing across currencies
    // would be noise rather than signal.
    const candidateCurrency = candidateCard.b3s__Currency__c;
    const shiftCurrency = shiftCard.b3s__Currency__c;
    if (candidateCurrency && shiftCurrency && candidateCurrency !== shiftCurrency) return results;

    // ---------------------------------------------------------------
    // Item matching, following the pay/bill engine's default item matching
    // ---------------------------------------------------------------

    // Overtime and Double Overtime depend on daily/weekly threshold rollups the scheduler cannot
    // see, so those items are excluded and the comparison is a straight-time one.
    const SKIP_RATE_TYPES = ['Overtime', 'Double Overtime'];
    const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

    // Time fields arrive normalised as 'HH:MM:SS.mmmZ'; tolerate a raw millis-of-day too.
    const parseTime = (value) => {
        if (value == null || value === '') return null;
        if (typeof value === 'number') return value;
        const parts = /^(\d{1,2}):(\d{2})(?::(\d{2}))?/.exec(String(value));
        if (!parts) return null;
        return Number(parts[1]) * 3600000 + Number(parts[2]) * 60000 + Number(parts[3] || 0) * 1000;
    };

    const dayMatches = (item, instant) => {
        if (!item.b3s__Days_Of_Week__c) return true;
        const weekday = WEEKDAYS[new Date(instant).getDay()];
        return `;${item.b3s__Days_Of_Week__c};`.includes(`;${weekday};`);
    };

    const midnight = (instant, addDays = 0) => {
        const d = new Date(instant);
        return new Date(d.getFullYear(), d.getMonth(), d.getDate() + addDays).getTime();
    };

    // Resolve a wall-clock time on the calendar day containing `dayInstant`.
    const atTime = (dayInstant, msOfDay) => {
        const d = new Date(dayInstant);
        return new Date(
            d.getFullYear(),
            d.getMonth(),
            d.getDate(),
            Math.floor(msOfDay / 3600000),
            Math.floor(msOfDay / 60000) % 60,
            Math.floor(msOfDay / 1000) % 60
        ).getTime();
    };

    // Project [Band_Start, Band_End) onto every calendar day the shift touches, one day back so a
    // band that wrapped from the previous evening is caught. Both blank = all-day catch-all.
    const bandWindows = (item) => {
        const bandStart = parseTime(item.b3s__Band_Start__c);
        const bandEnd = parseTime(item.b3s__Band_End__c);
        if (bandStart == null && bandEnd == null) return [[segStart, segEnd]];

        const start = bandStart ?? 0;
        const end = bandEnd ?? 0;
        const wraps = bandEnd == null || end < start;
        if (!wraps && end === start) return [];

        const windows = [];
        const lastDay = midnight(segEnd);
        for (let day = midnight(segStart, -1); day <= lastDay; day = midnight(day, 1)) {
            const windowStart = atTime(day, start);
            const windowEnd = atTime(wraps ? midnight(day, 1) : day, end);
            const clippedStart = Math.max(windowStart, segStart);
            const clippedEnd = Math.min(windowEnd, segEnd);
            if (clippedEnd > clippedStart) windows.push([clippedStart, clippedEnd]);
        }
        return windows;
    };

    // Claim [rangeStart, rangeEnd) out of the uncovered intervals for this item, emitting a block
    // per contiguous claimed piece. Pieces whose local start weekday fails the item's
    // Days_Of_Week stay uncovered for a later item to pick up.
    const consume = (uncovered, rangeStart, rangeEnd, item, rate, blocks) => {
        const remaining = [];
        for (const [pieceStart, pieceEnd] of uncovered) {
            const coveredStart = Math.max(pieceStart, rangeStart);
            const coveredEnd = Math.min(pieceEnd, rangeEnd);
            if (coveredEnd <= coveredStart || !dayMatches(item, coveredStart)) {
                remaining.push([pieceStart, pieceEnd]);
                continue;
            }
            blocks.push({ hours: (coveredEnd - coveredStart) / MS_HOUR, rate, item });
            if (pieceStart < coveredStart) remaining.push([pieceStart, coveredStart]);
            if (coveredEnd < pieceEnd) remaining.push([coveredEnd, pieceEnd]);
        }
        return remaining;
    };

    const interpret = (card) => {
        const base = card.b3s__Base_Pay_Rate__c != null ? Number(card.b3s__Base_Pay_Rate__c) : null;

        const items = (itemsByCard[card.Id] || [])
            .filter((item) => !SKIP_RATE_TYPES.includes(item.b3s__Rate_Type__c))
            .map((item, index) => ({ item, index }))
            .sort((a, b) => {
                const ap = a.item.b3s__Priority__c != null ? Number(a.item.b3s__Priority__c) : Number.MAX_SAFE_INTEGER;
                const bp = b.item.b3s__Priority__c != null ? Number(b.item.b3s__Priority__c) : Number.MAX_SAFE_INTEGER;
                return ap !== bp ? ap - bp : a.index - b.index;
            })
            .map((entry) => entry.item);

        // Explicit rate wins, else base multiplied, else the bare base rate.
        const rateOf = (item) => {
            if (item.b3s__Pay_Rate__c != null) return Number(item.b3s__Pay_Rate__c);
            if (item.b3s__Multiplier__c != null && base != null) return base * Number(item.b3s__Multiplier__c);
            return base;
        };

        const blocks = [];
        let uncovered = [[segStart, segEnd]];

        for (const item of items) {
            const rate = rateOf(item);
            if (rate == null || isNaN(rate)) continue;

            if (item.b3s__Behavior__c === 'Daily Flat') {
                // Once per shift, consumes no time.
                if (dayMatches(item, segStart)) blocks.push({ flat: rate, item });
                continue;
            }

            const bands = bandWindows(item);
            if (bands.length === 0) continue;

            if (item.b3s__Behavior__c === 'Hourly Start-Anchored') {
                // The shift starting inside the band claims the whole shift.
                if (bands.some(([s, e]) => segStart >= s && segStart < e)) {
                    uncovered = consume(uncovered, segStart, segEnd, item, rate, blocks);
                }
            } else if (item.b3s__Behavior__c === 'Hourly End-Anchored') {
                // The shift ending inside the band claims the whole shift, retroactively.
                if (bands.some(([s, e]) => segEnd > s && segEnd <= e)) {
                    uncovered = consume(uncovered, segStart, segEnd, item, rate, blocks);
                }
            } else {
                // Hourly Standard, and anything unset, bills the band overlap itself.
                for (const [s, e] of bands) {
                    uncovered = consume(uncovered, s, e, item, rate, blocks);
                }
            }
        }

        const uncoveredHours = uncovered.reduce((sum, [s, e]) => sum + (e - s) / MS_HOUR, 0);
        // The pay/bill engine leaves uncovered time unbilled and expects an all-day catch-all
        // item. Here both cards are priced over the same hours instead, so a card whose bands
        // simply miss the shift is not made to look cheap. A card with no base rate and uncovered
        // time cannot be priced at all, and the comparison is abandoned.
        if (uncoveredHours > 0 && base == null) return null;

        const cost =
            blocks.reduce((sum, block) => sum + (block.flat != null ? block.flat : block.hours * block.rate), 0) +
            uncoveredHours * (base ?? 0);

        return { cost, uncoveredHours, blocks };
    };

    const candidate = interpret(candidateCard);
    const shift = interpret(shiftCard);
    if (!candidate || !shift || shift.cost <= 0) return results;

    const currency = candidateCurrency || shiftCurrency || '';
    const money = (value) => `${currency}${currency ? ' ' : ''}${value.toFixed(2)}`;
    const hours = ((segEnd - segStart) / MS_HOUR).toFixed(2).replace(/\.?0+$/, '');

    console.log(`Scheduler Rate Card [${contactId}]`, {
        candidateCard, candidateScore: candidateMatch.score, shiftCard, shiftScore: shiftMatch.score, candidate, shift
    });

    if (candidate.cost <= shift.cost) {
        results.push(
            new EvaluationResult({
                event: event,
                category: 'Rate Card',
                detail: `✅ ${candidateCard.Name} costs ${money(candidate.cost)} vs shift ${money(shift.cost)} over ${hours}h`,
                points: 0
            })
        );
        return results;
    }

    const pct = ((candidate.cost - shift.cost) / shift.cost) * 100;
    const points = pct <= 10 ? -5 : pct <= 25 ? -10 : -20;

    results.push(
        new EvaluationResult({
            event: event,
            category: 'Rate Card',
            detail: `💰 ${candidateCard.Name} costs ${money(candidate.cost)} vs shift ${money(shift.cost)} over ${hours}h (+${Math.round(pct)}%)`,
            points: points
        })
    );

    return results;
}
        ]]></value>
    </values>
    <values>
        <field>b3s__Type__c</field>
        <value xsi:type="xsd:string">Scheduling</value>
    </values>
</CustomMetadata>
