How to set Maker Fields in FAM Records through FAM Process

define(['N/runtime', 'N/record', 'N/search'], (runtime, record, search) => {
    "use strict"
    /**
  * Retrieves the posting reference (journal ID) for a given asset.
  *
  * @param {string} assetId - The internal ID of the asset to search for.
  * @returns {string|null} - The posting reference (journal ID) if found, otherwise null.
  */
    function toGetAssetTransferId(assetId) {
        try {
            let customrecord_ncfar_deprhistorySearchObj = search.create({
                type: "customrecord_ncfar_deprhistory",
                filters: [
                    ["custrecord_deprhistasset", "anyof", assetId]
                ],
                columns: [
                    search.createColumn({
                        name: "internalid",
                        summary: "MAX",
                        label: "Internal ID"
                    }),
                    search.createColumn({
                        name: "internalid",
                        join: "CUSTRECORD_DEPRHISTJOURNAL",
                        summary: "MAX",
                        label: "Internal ID"
                    })
                ]
            });


            let searchResultCount = customrecord_ncfar_deprhistorySearchObj.runPaged().count;
            log.debug("customrecord_ncfar_deprhistorySearchObj result count", searchResultCount);


            let postingReference = null;


            customrecord_ncfar_deprhistorySearchObj.run().each(function (result) {
                // Retrieve the posting reference (journal ID)
                postingReference = result.getValue({
                    name: "internalid",
                    join: "CUSTRECORD_DEPRHISTJOURNAL",
                    summary: "MAX",
                });
                return true; // Continue the search
            });


            return postingReference;
        } catch (error) {
            log.error("Error in toGetAssetTransferId", error.message);
            return null;
        }
    }


    /**
    * Retrieves a list of FAM (Fixed Asset Management) processes based on the given process ID and internal ID.
    * The function searches for FAM records and extracts specific fields to build an object mapping the process list items to their respective process IDs and triggered users.
    * 
    * @param {string} processId - The ID of the process to search for.
    * @param {number|string} internalid - The internal ID of the record to filter the search results.
    * @returns {Object} An object where each key represents a process list item, and the value is an object containing the process ID and triggered user.
    */
    function toGetFAMProcess(processId, internalid) {
        try {
            let customrecord_fam_processSearchObj = search.create({
                type: "customrecord_fam_process",
                filters: [
                    ["custrecord_fam_procid", "is", processId],
                    "AND",
                    ["internalid", "anyof", internalid]
                ],
                columns: [
                    search.createColumn({ name: "custrecord_fam_procid", label: "Process ID" }),
                    search.createColumn({ name: "custrecord_fam_procuser", label: "Triggered By" }),
                    search.createColumn({ name: "custrecord_fam_procstatus", label: "Status" }),
                    search.createColumn({ name: "custrecord_fam_procparams", label: "Parameters" }),
                    search.createColumn({ name: "custrecord_fam_procstateval", label: "State Values" })
                ]
            });


            let searchResultCount = customrecord_fam_processSearchObj.runPaged().count;
            log.debug("customrecord_fam_processSearchObj result count", searchResultCount);


            let proplistObject = {};
            if (searchResultCount > 0) {
                customrecord_fam_processSearchObj.run().each(function (result) {
                    try {
                        let processIdValue = result.getValue({ name: "custrecord_fam_procid" });
                        let parametersValue = result.getValue({ name: "custrecord_fam_procparams" });
                        let triggeredBy = result.getValue({ name: "custrecord_fam_procuser" });
                        let parametersObj = JSON.parse(parametersValue);


                        log.debug("processIdValue", processIdValue);
                        log.debug("parametersValue", parametersValue);
                        if (processIdValue == 'proposal' || processIdValue == 'assetGeneration' || processIdValue == 'assetCreation') {
                            if (parametersObj.proplist) {
                                let proplistArray = parametersObj.proplist.split(':');
                                proplistArray.forEach(function (proplistItem) {
                                    proplistObject[proplistItem] = {
                                        processId: processIdValue,
                                        triggeredBy: triggeredBy
                                    };
                                });
                                log.debug("Proplist Object", proplistObject);
                            }
                        }
                        if (processIdValue == 'assetSplit') {
                            if (parametersObj.assetsToSplit) {
                                Object.keys(parametersObj.assetsToSplit).forEach(function (assetId) {
                                    let assetDetails = parametersObj.assetsToSplit[assetId];


                                    if (assetDetails.recs) {
                                        assetDetails.recs.forEach(function (recId) {
                                            proplistObject[recId] = {
                                                processId: processIdValue,
                                                triggeredBy: triggeredBy
                                            };
                                        });
                                        log.debug("Proplist Object for assetSplit", proplistObject);
                                    }
                                });
                            }
                        }
                        if (processIdValue == 'depreciation') {
                            if (parametersObj.journals) {
                                let journalsArray = parametersObj.journals.split(',');
                                journalsArray.forEach(function (journalId) {
                                    proplistObject[journalId] = {
                                        processId: processIdValue,
                                        triggeredBy: triggeredBy
                                    };
                                });
                                log.debug("Proplist Object for depreciation", proplistObject);
                            }


                        }
                        if (processIdValue == 'disposal') {
                            if (parametersObj.recsToProc) {
                                Object.keys(parametersObj.recsToProc).forEach(function (assetId) {
                                    let assetName = search.lookupFields({
                                        type: 'customrecord_ncfar_asset', // Replace with correct record type
                                        id: assetId,
                                        columns: ['name']
                                    }).name;
                                    let disposalId = getDisposalDetails(assetName)
                                    proplistObject[disposalId] = {
                                        processId: processIdValue,
                                        triggeredBy: triggeredBy
                                    };
                                });
                                log.debug("Proplist Object for disposal", proplistObject);
                            }
                        }
                        if (processIdValue === 'revaluation') {
                            if (parametersObj.recsToRevalue) {
                                parametersObj.recsToRevalue.forEach(function (revalueObj) {
                                    if (revalueObj.journal) {
                                        let journalId = revalueObj.journal;
                                        proplistObject[journalId] = {
                                            processId: processIdValue,
                                            triggeredBy: triggeredBy
                                        };
                                    }
                                });
                                log.debug("Proplist Object for revaluation", proplistObject);
                            }
                        }
                        if (processIdValue == 'transfer') {
                            if (parametersObj.recsToProcess) {
                                Object.keys(parametersObj.recsToProcess).forEach(function (assetId) {
                                    log.debug("assetDetails", assetId)
                                    let journalId = toGetAssetTransferId(assetId)
                                    log.debug("journalId", journalId)
                                    // let journalId = parametersObj.journals || 'journalIdNotFound'; // Replace with actual logic if needed


                                    proplistObject[journalId] = {
                                        processId: processIdValue,
                                        triggeredBy: triggeredBy
                                    };
                                });
                                log.debug("Proplist Object for transfer", proplistObject);
                            }
                        }
                        return true;
                    } catch (error) {
                        log.error("Error processing FAM process result", error.message);
                        return false;
                    }
                });
            }
            return proplistObject;
        } catch (e) {
            log.error("Error in toGetFAMProcess", e.message);
        }
    }


    /**
     * Sets the maker field for the asset proposal record.
     * 
     * @param {string} recordId - The ID of the asset proposal record.
     * @param {string} triggeredByValue - The ID of the user who triggered the process.
     */
    function setMakerFieldForAssetProposal(recordId, triggeredByValue) {
        try {
            record.submitFields({
                type: 'customrecord_ncfar_assetproposal',
                id: recordId,
                values: {
                    custrecord_jj_maker_fam_asset: triggeredByValue,
                    isinactive: true,
                    custrecord_propstatus: null
                }
            });
            log.debug('Setting Maker field for Asset Proposal', 'Record ID: ' + recordId + ', Triggered By: ' + triggeredByValue);
        } catch (error) {
            log.error('Error setting Maker field for Asset Proposal', error.message);
        }
    }
    /**
    * Retrieves the internal ID of a transaction based on the provided asset name.
    *
    * This function searches for transactions of type "Custom101" where the memo contains the given asset name.
    * It returns the internal ID of the first matching transaction found.
    *
    * @param {string} assetName - The asset name to search for in the transaction memo.
    * @returns {string|null} - The internal ID of the matching transaction or `null` if no matching transaction is found.
    */
    function getDisposalDetails(assetName) {
        try {
            let transactionSearchObj = search.create({
                type: "transaction",
                settings: [{ "name": "consolidationtype", "value": "ACCTTYPE" }],
                filters: [
                    ["type", "anyof", "Custom101"],
                    "AND",
                    ["memo", "contains", assetName]
                ],
                columns: [
                    search.createColumn({ name: "internalid", label: "Internal ID" })
                ]
            });
            let searchResultCount = transactionSearchObj.runPaged().count;
            log.debug("transactionSearchObj result count", searchResultCount);
            let internalId = ''
            if (searchResultCount) {
                transactionSearchObj.run().each(function (result) {
                    internalId = result.getValue({ name: "internalid" });


                });


                log.debug("Collected Internal IDs", internalId);


                // Return the collected internal IDs
                return internalId;
            }
        } catch (error) {
            log.error('Error@getDisposalDetails', error.message);
        }
    }
    /**
     * Sets the maker field for the asset record.
     * 
     * @param {string} proposalId - The ID of the asset proposal record.
     * @param {string} triggeredByValue - The ID of the user who triggered the process.
     */
    function setMakerFieldForAsset(proposalId, triggeredByValue) {
        try {
            let assetProposalRecord = record.load({
                type: 'customrecord_ncfar_assetproposal',
                id: proposalId
            });


            let propAssetId = assetProposalRecord.getValue('custrecord_propasset');
            log.debug('Asset Proposal Record Loaded', 'Proposal ID: ' + proposalId + ', propAssetId: ' + propAssetId);


            if (propAssetId) {
                record.submitFields({
                    type: 'customrecord_ncfar_asset',
                    id: propAssetId,
                    values: {
                        custrecord_jj_maker_fam: triggeredByValue,
                        custrecord_jj_approval_status_fam: 3
                    }
                });
                log.debug('Setting Maker field for Asset', 'Asset ID: ' + propAssetId + ', Triggered By: ' + triggeredByValue);
            }
        } catch (error) {
            log.error('Error setting Maker field for Asset', error.message);
        }
    }
    /**
     * Sets the maker field for the asset record.
     * 
     * @param {string} proposalId - The ID of the asset proposal record.
     * @param {string} triggeredByValue - The ID of the user who triggered the process.
     */
    function setMakerFieldForAssetCreation(proposalId, triggeredByValue) {
        try {
            let assetProposalRecord = record.load({
                type: 'customrecord_ncfar_assetproposal',
                id: proposalId
            });
            assetProposalRecord.setValue({
                fieldId: 'custrecord_jj_maker_fam_asset',
                value: triggeredByValue
            });
            assetProposalRecord.setValue({
                fieldId: 'custrecord_jj_approval_status_fam_asset',
                value: 3
            });
            assetProposalRecord.save();
            let propAssetId = assetProposalRecord.getValue('custrecord_propasset');
            log.debug('Asset Proposal Record Loaded', 'Proposal ID: ' + proposalId + ', propAssetId: ' + propAssetId);


            if (propAssetId) {
                record.submitFields({
                    type: 'customrecord_ncfar_asset',
                    id: propAssetId,
                    values: {
                        custrecord_jj_maker_fam: triggeredByValue,
                        isinactive: true
                    }
                });
                log.debug('Setting Maker field for Asset', 'Asset ID: ' + propAssetId + ', Triggered By: ' + triggeredByValue);
            }
        } catch (error) {
            log.error('Error@setMakerFieldForAssetCreation', error.message);
        }
    }
    /**
    * Sets the maker field for the asset record.
    * 
    * @param {string} proposalId - The ID of the asset proposal record.
    * @param {string} triggeredByValue - The ID of the user who triggered the process.
    */
    function setMakerFieldsAssetSplit(assetId, triggeredByValue) {
        try {
            if (assetId) {
                record.submitFields({
                    type: 'customrecord_ncfar_asset',
                    id: assetId,
                    values: {
                        custrecord_jj_maker_fam: triggeredByValue || '',
                        custrecord_jj_approval_status_fam: 3
                    }
                });
                log.debug('Setting Maker field for Asset', 'Asset ID: ' + assetId + ', Triggered By: ' + triggeredByValue);
            }


        } catch (error) {
            log.error('Error@setMakerFieldsAssetSplit', error.message);
        }
    }
    /**
     * Sets the maker field for the depreciation record.
     * 
     * @param {string} proposalId - The ID of the asset proposal record.
     * @param {string} triggeredByValue - The ID of the user who triggered the process.
     */
    function setMakerFieldForTransaction(journalId, triggeredByValue, recordType) {


        try {
            if (journalId) {
                record.submitFields({
                    type: recordType,
                    id: journalId,
                    values: {
                        custbody_jj_maker: triggeredByValue || '',
                        transtatus: 'A'
                    }
                });
                log.debug('Setting Maker field for Asset', 'Asset ID: ' + journalId + ', Triggered By: ' + triggeredByValue);
            }


        } catch (error) {
            log.error('Error@setMakerFieldForTransaction', error.message);
        }
    }


    /**
     * Handles the creation or editing of FAM records.
     * 
     * @param {Object} scriptContext - The context object containing information about the script execution.
     */
    function handleFAMRecords(scriptContext) {
        try {
            let newRecordId = scriptContext.newRecord.id;
            let recordType = scriptContext.newRecord.type;
            let newRec = scriptContext.newRecord;
            let processId = newRec.getValue({ fieldId: 'custrecord_fam_procid' });


            if (processId === 'proposal' || processId === 'assetGeneration' || processId === 'assetSplit' || processId == 'assetCreation' || processId == 'depreciation' || processId == 'disposal' || processId == 'revaluation' || processId == 'transfer') {
                let processObj = toGetFAMProcess(processId, newRecordId);
                log.debug("processObj", processObj)
                Object.keys(processObj).forEach(function (key) {
                    log.debug("processObj[key].processId", processObj[key].processId)
                    try {
                        if (processObj[key].processId === 'proposal') {
                            setMakerFieldForAssetProposal(key, processObj[key].triggeredBy);
                        } else if (processObj[key].processId === 'assetGeneration') {
                            setMakerFieldForAsset(key, processObj[key].triggeredBy);
                        }
                        else if (processObj[key].processId === 'assetSplit') {
                            setMakerFieldsAssetSplit(key, processObj[key].triggeredBy)
                        }
                        else if (processObj[key].processId === 'assetCreation') {
                            setMakerFieldForAssetCreation(key, processObj[key].triggeredBy)
                        }
                        else if (processObj[key].processId === 'depreciation') {
                            setMakerFieldForTransaction(key, processObj[key].triggeredBy, 'customtransaction_fam_depr_jrn')
                        }
                        else if (processObj[key].processId === 'disposal') {


                            setMakerFieldForTransaction(key, processObj[key].triggeredBy, 'customtransaction_fam_disp_jrn')
                        }
                        else if (processObj[key].processId === 'revaluation') {


                            setMakerFieldForTransaction(key, processObj[key].triggeredBy, 'customtransaction_fam_revaluation_jrn')
                        }
                        else if (processObj[key].processId === 'transfer') {


                            setMakerFieldForTransaction(key, processObj[key].triggeredBy, 'customtransaction_fam_transfer_jrn')
                        }
                    } catch (error) {
                        log.error('Error processing FAM record', error.message);
                    }
                });
            }
        } catch (error) {
            log.error('Error handling FAM records', error.message);
        }
    }


    /**
     * Handles the submission of records to set maker fields based on the record type.
     * 
     * @param {Object} scriptContext - The context object containing information about the script execution.
     */
    function handleMakerField(scriptContext) {
        try {
            let newRecordId = scriptContext.newRecord.id;
            let recordType = scriptContext.newRecord.type;
            let currentUserId = runtime.getCurrentUser().id;


            if (recordType === 'customrecord_ncfar_assetproposal' && scriptContext.type === scriptContext.UserEventType.CREATE) {
                if (currentUserId !== -4) {
                    record.submitFields({
                        type: recordType,
                        id: newRecordId,
                        values: {
                            custrecord_jj_maker_fam_asset: currentUserId,
                            isinactive: true,
                            custrecord_propstatus: null
                        }
                    });
                }
            } else if (recordType === 'customrecord_ncfar_asset' && scriptContext.type === scriptContext.UserEventType.CREATE) {
                if (currentUserId !== -4) {
                    record.submitFields({
                        type: recordType,
                        id: newRecordId,
                        values: {
                            custrecord_jj_maker_fam: currentUserId,
                            isinactive: true
                        }
                    });
                }
            }
            else if ((recordType === 'customtransaction_fam_depr_jrn' || recordType === 'customtransaction_fam_revaluation_jrn' || recordType === 'customtransaction_fam_disp_jrn' || recordType === 'customtransaction_fam_transfer_jrn') && scriptContext.type === scriptContext.UserEventType.CREATE) {
                if (currentUserId !== -4) {
                    record.submitFields({
                        type: recordType,
                        id: newRecordId,
                        values: {
                            custbody_jj_maker: currentUserId,
                        }
                    });
                }
            }


        } catch (error) {
            log.error('Error handling Maker field', error.message);
        }
    }


    /**
     * Defines the function definition that is executed after a record is submitted.
     * 
     * @param {Object} scriptContext
     * @param {Record} scriptContext.newRecord - The new record object.
     * @param {Record} scriptContext.oldRecord - The old record object.
     * @param {string} scriptContext.type - The type of trigger; use values from the context.UserEventType enum.
     * @since 2015.2
     */
    const afterSubmit = (scriptContext) => {
        try {
            if (scriptContext.type === scriptContext.UserEventType.CREATE || scriptContext.type === scriptContext.UserEventType.EDIT) {
                handleFAMRecords(scriptContext);
            }
            handleMakerField(scriptContext);
        } catch (e) {
            log.error('Error in afterSubmit', e.message);
        }
    };


    return { afterSubmit };
});

Leave a comment

Your email address will not be published. Required fields are marked *