Untitled

Anonymous
plain_text
05/05/2026 6:21 AM
3.6 KB
14
Indexable
var ACWAPP = ACWAPP || {};

ACWAPP.AwardAmount = (function () {
    const SUBGRID_NAME = "RelatedCaseRef";
    const AMOUNT_FIELD = "acwapp_amountofrewardgrantedtoeachinformant";

    const CONFIG_TABLE = "acwapp_awardconfiguration";
    const CONFIG_AMOUNT_FIELD = "acwapp_totalawardamount";

    function OnLoad(executionContext) {
        const formContext = executionContext.getFormContext();

        window.setTimeout(function () {
            validateAmount(formContext);
            registerSubgridOnLoad(formContext);
        }, 1000);
    }

    function OnAmountChange(executionContext) {
        const formContext = executionContext.getFormContext();
        validateAmount(formContext);
    }

    function registerSubgridOnLoad(formContext) {
        const subgrid = formContext.getControl(SUBGRID_NAME);

        if (subgrid && !subgrid._awardAmountRegistered) {
            subgrid.addOnLoad(function () {
                validateAmount(formContext);
            });

            subgrid._awardAmountRegistered = true;
        }
    }

    async function getTotalAwardAmount() {
        const result = await Xrm.WebApi.retrieveMultipleRecords(
            CONFIG_TABLE,
            "?$select=" + CONFIG_AMOUNT_FIELD + "&$filter=statecode eq 0&$top=1"
        );

        if (!result.entities || result.entities.length === 0) {
            return null;
        }

        return result.entities[0][CONFIG_AMOUNT_FIELD];
    }

    async function validateAmount(formContext) {
        const subgrid = formContext.getControl(SUBGRID_NAME);
        const amountAttr = formContext.getAttribute(AMOUNT_FIELD);
        const amountCtrl = formContext.getControl(AMOUNT_FIELD);

        if (!subgrid || !amountAttr || !amountCtrl) return;

        const grid = subgrid.getGrid();
        if (!grid) return;

        const rowCount = grid.getTotalRecordCount();

        amountCtrl.clearNotification("amount_limit");

        if (rowCount <= 0) return;

        const totalAmount = await getTotalAwardAmount();

        if (totalAmount === null) {
            amountCtrl.setNotification(
                "Award configuration is missing. Please contact an administrator.",
                "amount_limit"
            );
            return;
        }

        const perRowAmount = totalAmount / rowCount;
        const currentAmount = amountAttr.getValue();

        if (currentAmount !== null && currentAmount > perRowAmount) {
            amountCtrl.setNotification(
                "Amount cannot exceed " + perRowAmount + ".",
                "amount_limit" 
            );
        }
    }

    return {
        OnLoad: OnLoad,
        OnAmountChange: OnAmountChange
    };
})();
Editor is loading...
Leave a Comment