User Event Script to update JSON file for Custom Commerce Categories : (SuiteCommerce MyAccount) SCMA

Scenario:

We need to create a JSON file of custom categories that need to be displayed on the website, it is Suite Commerce MyAccount so there is no default feature for Commerce categories, so we have created a custom record for the same, and In this script we are creating a JSON file for storing all the values of records under the custom Commerce category.

Script:

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 
 * Author: Jobin & Jismi IT Services LLP 

 * Date: 28/09/2023

 * Version: 1.0
 */
define(['N/record', 'N/runtime', 'N/search', 'N/file'],
    /**
     * @param{record} record
     * @param{runtime} runtime
     * @param{search} search
     * @param{search} file
     */
    (record, runtime, search, file) => {
        /**
         * Defines the function definition that is executed after record is submitted.
         * @param {Object} scriptContext
         * @param {Record} scriptContext.newRecord - New record
         * @param {Record} scriptContext.oldRecord - Old record
         * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
         * @since 2015.2
         */
        const afterSubmit = (scriptContext) => {
            try {
                try {
                    var topLevelCategories;
                    let fields = {
                        'id': 'internalid',
                        'custrecord_parent_category': 'parentCategory',
                        'name': 'name',
                        'custrecord_category_order': 'Order',
                        'custrecord_url_fragment': 'urlfragment',
                        'custrecord_category_meta_description': 'metadescription',
                        'custrecord_category_meta_keyword': 'metakeywords',
                        'custrecord_category_page_title': 'pagetitle'
                    };
                    let columns = [search.createColumn({
                        name: "name",
                        sort: search.Sort.ASC,
                        label: "Name"
                    })];
                    for (let key in fields) {
                        columns.push(search.createColumn({
                            name: key,
                            label: key
                        }));
                    }
                    const CUSTOMRECORDSEARCH = search.create({
                        type: 'customrecord_commerce_category',
                        title: 'Commerce Category',
                        columns: columns
                    })
                    let customCategoryListResult = [];
                    let childList = {};
                    CUSTOMRECORDSEARCH.run().each(function(result) {
                        let baseObj = {
                            "categories": [],
                            "internalid": "",
                            "parentCategory": "",
                            "name": "",
                            "Order": "",
                            "urlfragment": "",
                            "metadescription": "",
                            "metakeywords": "",
                            "pagetitle": ""
                        };
                        let parent = result.getValue({
                            name: 'custrecord_sc_categories_facet_parent'
                        });
                        for (let key1 in fields) {
                            baseObj[fields[key1]] = result.getValue({
                                name: key1
                            });
                        }
                        if (!parent) {
                            customCategoryListResult.push(baseObj);
                        } else {
                            if (childList[parent]) {
                                childList[parent].push(baseObj);
                            } else {
                                childList[parent] = [];
                                childList[parent].push(baseObj);
                            }
                        }
                        return true;
                    });
                    let categoryMap = {};
                    customCategoryListResult.forEach(function(category) {
                        category.categories = []; // Initialize the 'categories' array
                        categoryMap[category.internalid] = category;
                    });
                    // Iterate through the categories and add child categories to parent categories
                    customCategoryListResult.forEach(function(category) {
                        let parentID = category["parentCategory"];
                        if (parentID && categoryMap[parentID]) {
                            categoryMap[parentID].categories.push(category);
                        }
                    });
                    // Filter out the top-level categories (categories with no parent)
                    topLevelCategories = customCategoryListResult.filter(function(category) {
                        return !category["parentCategory"];
                    });
                    //Adding level and custom url values for displaying on the website
                    topLevelCategories.forEach(function(category) {
                        category['level'] = '1';
                        category['customurl'] = '/items?cid=' + category["internalid"]
                        if (category.categories.length > 0) {
                            category.categories.forEach(level1 => {
                                level1['level'] = '2';
                                level1['customurl'] = '/items?cid=' + level1["internalid"]
                                if (level1.categories.length > 0) {
                                    level1.categories.forEach(level2 => {
                                        level2['level'] = '3';
                                        level2['customurl'] = '/items?cid=' + level2["internalid"]
                                    });
                                }
                            });
                        }
                    });
                } catch (error) {
                    log.debug("customRecord load error", error);
                }
                try {
                    let contentString = JSON.stringify(topLevelCategories)
                    let fileObj = file.create({
                        name: 'CustomCommerceCategory',
                        fileType: file.Type.JSON,
                        contents: contentString,
                        folder: 2973819,
                        isOnline: true
                    });
                    fileObj.save();
                } catch (error) {
                    log.debug("file loading error", error);
                }
            } catch (error) {
                log.debug("Error in category update", error);
            }
        }
        return {
            afterSubmit
        }
    });

Leave a comment

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