Download Estimate CSV File

User Event

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
define([],


    () => {
            /**
             * Defines the function definition that is executed before record is loaded.
             * @param {Object} scriptContext
             * @param {Record} scriptContext.newRecord - New record
             * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
             * @param {Form} scriptContext.form - Current form
             * @param {ServletRequest} scriptContext.request - HTTP request information sent from the browser for a client action only.
             * @since 2015.2
             */
            const beforeLoad = (scriptContext) => {
                    try{


                            if (scriptContext.type == 'view') {
                                    scriptContext.form.addButton({
                                            id: 'custpage_downloadscv',
                                            label: 'Download CSV',
                                            functionName: 'estimateCSVDownload'
                                    });


                                    scriptContext.form.clientScriptFileId = 3353;
                            }


                    }
                    catch (error) {
                            log.debug('catchError', error)
                    }
            }




            return {beforeLoad}


    });

Client Script
/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
 define(['N/url','N/currentRecord','N/search'],


 function(url,currentRecord,search) {


     let scriptContextResponse;
     /**
      * Function to be executed after page is initialized.
      *
      * @param {Object} scriptContext
      * @param {Record} scriptContext.currentRecord - Current form record
      * @param {string} scriptContext.mode - The mode in which the record is being accessed (create, copy, or edit)
      *
      * @since 2015.2
      */
     function pageInit(scriptContext) {
         console.log("scriptContext",scriptContext.mode)
         scriptContextResponse = scriptContext.response;
     }


     /**
      * @description Invoke on the custom button(Payment voucher Print) click available in the  Bill Payment record
      */
     function  estimateCSVDownload(){
         try{
             let internalIds = currentRecord.get().id;
             let currenturl = url.resolveScript({
                 scriptId: "customscript_jj_sl_download_csv_stbuk_52",
                 deploymentId: "customdeploy_jj_sl_download_csv_stbuk_52",
                 params:{
                     internalIds:internalIds
                 }
             })
             window.location.href = currenturl;
            // window.open(currenturl);
             
             
         }
         catch (e) {
             log.debug("error@billPaymentPrint", e)
         }


     }
    
     return {
         pageInit: pageInit,
         estimateCSVDownload : estimateCSVDownload
     };


 });

Suitelet 

/**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 */
define(['N/search', 'N/file', 'N/log', './papaparse.min.js'], function (search, file, log, papa) {
    let documentNumber;

    const onRequest = (scriptContext) => {
        try {
            let recIds = scriptContext.request.parameters.internalIds;

            let csvObj = getEstimateObj(recIds);

            scriptContext.response.setHeader({
                name: 'Content-Type',
                value: 'text/csv'
            });

            let fileName = documentNumber + '-' + getTimestamp();
            scriptContext.response.setHeader({
                name: 'Content-Disposition',
                value: 'attachment; filename="' + fileName + '.csv"'
            });

            scriptContext.response.writeFile(csvObj, false);
        } catch (e) {
            log.debug("error@onRequest", e);
        }
    };

    /**
     * @description Function to get the estimate record details and generate CSV file
     * @param {Array} internalIds - internalIds of the estimate record
     * @returns {Object} - CSV file
     */
    function getEstimateObj(internalIds) {
        try {
            let estimateSearchObj = search.create({
                type: "estimate",
                filters: [
                    ["type", "anyof", "Estimate"],
                    "AND",
                    ["shipping", "is", "F"],
                    "AND",
                    ["cogs", "is", "F"],
                    "AND",
                    ["taxline", "is", "F"],
                    "AND",
                    ["mainline", "is", "F"],
                    "AND",
                    ["internalid", "anyof", internalIds],
                    "AND",
                    ["transactiondiscount", "is", "F"]
                ],
                columns: [
                    search.createColumn({ name: "tranid", label: "Document Number" }),
                    search.createColumn({ name: "billaddress", label: "Billing Address" }),
                    search.createColumn({ name: "shipaddress", label: "Shipping Address" }),
                    search.createColumn({ name: "entity", label: "Name" }),
                    search.createColumn({ name: "trandate", label: "Date" }),
                    search.createColumn({ name: "duedate", label: "Due Date/Receive By" }),
                    search.createColumn({ name: "salesrep", label: "Sales Rep" }),
                    search.createColumn({ name: "quantity", label: "Quantity" }),
                    search.createColumn({ name: "rate", label: "Item Rate" }),
                    search.createColumn({
                        name: "formulacurrency",
                        formula: "CASE WHEN {itemtype}='Description' AND {amount} = 0 THEN null ELSE {amount} END",
                        label: "Formula (Currency)"
                    }),
                    search.createColumn({ name: "custbody_messagetocustomer", label: "Message to Customer" }),
                    search.createColumn({ name: "custbody_contactname", label: "Contact Name" }),
                    search.createColumn({ name: "custbody_ukservicelevel", label: "UK Shipping Service Level" }),
                    search.createColumn({ name: "terms", label: "Terms" }),
                    search.createColumn({ name: "custbody_ezconceptleadtime", label: "EZ Concept Lead Time" }),
                    search.createColumn({ name: "custbody_originalprojectid", label: "Original Project ID" }),
                    search.createColumn({ name: "custcol_ukwallthickness", label: "UK-Wall Thickness" }),
                    search.createColumn({ name: "custcol_ukframeheight", label: "UK-Frame Height" }),
                    search.createColumn({ name: "custcol_ukframewidth", label: "UK-Frame Width" }),
                    search.createColumn({ name: "custcol_ukstrike1", label: "UK-Strike 1" }),
                    search.createColumn({ name: "custcol_ukhanding", label: "UK-Handing" }),
                    search.createColumn({ name: "custcol_ukfirerating", label: "UK-Fire Rating" }),
                    search.createColumn({ name: "custcol_ukhinges", label: "UK-Hinges" }),
                    search.createColumn({ name: "custcol_labeldoornumber", label: "Label Door Number" }),
                    search.createColumn({ name: "custcol_ezwallthickness", label: "Wall Thickness" }),
                    search.createColumn({ name: "custcol_ezdoorheight", label: "Door Height" }),
                    search.createColumn({ name: "custcol_doorwidth", label: "Door Width" }),
                    search.createColumn({ name: "custcol_ezstriketype", label: "Strike Type" }),
                    search.createColumn({ name: "custcol_ezhingehand", label: "Hinge Hand" }),
                    search.createColumn({ name: "custcol_ezfirerated", label: "Fire Rated" }),
                    search.createColumn({ name: "custcol_ezhingeprep", label: "Hinge Prep" })
                ]
            });

            let lineCount = 0;
            let csvContent = [];

            estimateSearchObj.run().each(function (result) {
                lineCount++;

                if (lineCount == 1) {
                    documentNumber = result.getValue({ name: "tranid" });

                    let header = [
                        'Document Number', 'Bill To', 'Deliver To', 'Account #', 'Quote Date', 'Quote Expiration', 
                        'Entered By', 'Message to Customer', 'Contact', 'Shipping Service Level', 'Terms', 
                        'Production Lead Time', 'Project'
                    ];
                    csvContent.push(header);

                    documentNumber = result.getValue({name: "tranid"});
                 let billingAddress = sanitizeData(result.getValue({name: "billaddress"}) || '');
                 let shippingAddress = sanitizeData(result.getValue({name: "shipaddress"}) || '');
                 let entity = sanitizeData(result.getText({name: "entity"}) || '');
                 if(entity){
                        entity = entity.split(' ')[0];
                 }
                 let transactionDate = sanitizeData(result.getValue({name: "trandate"}) || '');
                 let dueDate = sanitizeData(result.getValue({name: "duedate"}) || '');
                 let salesRep = sanitizeData(result.getText({name: "salesrep"}) || '');
                 let messageToCustomer = sanitizeData(result.getValue({name: "custbody_messagetocustomer"}) || '');
                 let contactName = sanitizeData(result.getValue({name: "custbody_contactname"}) || '');
                 let ukShippingServiceLevel = sanitizeData(result.getText({name: "custbody_ukservicelevel"}) || '');
                 let terms = sanitizeData(result.getText({name: "terms"}) || '');
                 let ezConceptLeadTime = sanitizeData(result.getValue({name: "custbody_ezconceptleadtime"}) || '');
                 let originalProjectId = sanitizeData(result.getValue({name: "custbody_originalprojectid"}) || '');
                    
                    let row = [
                        documentNumber,
                        billingAddress,
                        shippingAddress,
                        entity,
                        transactionDate,
                        dueDate,
                        salesRep,
                        messageToCustomer,
                        contactName,
                        ukShippingServiceLevel,
                        terms,
                        ezConceptLeadTime,
                        originalProjectId
                    ];
                    csvContent.push(row);
                    csvContent.push("n");
                  csvContent.push(['Wall','Height','Width','Strike','Hand','FR','Prep','Door','Quantity','Rate','Amount'])
                }

                // Append Item details
                let itemRow = [
                    sanitizeData(result.getText({name: "custcol_ukwallthickness"}) || result.getValue({name: "custcol_ezwallthickness"}) || ' '),
                    sanitizeData(result.getText({name: "custcol_ukframeheight"}) || result.getValue({name: "custcol_ezdoorheight"}) || ' '),
                    sanitizeData(result.getText({name: "custcol_ukframewidth"}) || result.getValue({name: "custcol_doorwidth"}) || ' '),
                    sanitizeData(result.getText({name: "custcol_ukstrike1"}) || result.getValue({name: "custcol_ezstriketype"}) || ' '),
                    sanitizeData(result.getText({name: "custcol_ukhanding"}) || result.getText({name: "custcol_ezhingehand"}) || ' '),
                    sanitizeData(result.getText({name: "custcol_ukfirerating"}) || result.getText({name: "custcol_ezfirerated"}) ||  ' '),
                    sanitizeData(result.getText({name: "custcol_ukhinges"}) || result.getText({name: "custcol_ezhingeprep"}) || ' '),
                    sanitizeData(result.getValue({name: "custcol_labeldoornumber"}) || ' '),
                    sanitizeData(result.getValue({name: "quantity"}) || ' '),
                    sanitizeData(result.getValue({name: "rate"}) || ' '),
                    sanitizeData(result.getValue({name: "formulacurrency"}) || ' '),
                ];

                csvContent.push(itemRow);
                return true;
            });

            // Convert CSV content to a CSV string using Papa.unparse
            let csvFileData = papa.unparse(csvContent); // Use Papa.unparse to generate CSV

            // Create the CSV file
            let csvFile = file.create({
                name: "estimate.csv",
                fileType: file.Type.CSV,
                contents: csvFileData
            });

            return csvFile;

        } catch (e) {
            log.debug("error@getEstimateObj", e);
        }
    }

    /**
     * @description Function to sanitize data by removing newlines
     * @param {String} data
     * @returns {String} sanitized data
     */
    function sanitizeData(data) {
        return data.replace(/[rn]+/g, ' ').trim();
    }

    function getTimestamp() {
        let currentDate = new Date();
        let year = currentDate.getFullYear();
        let month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
        let day = currentDate.getDate().toString().padStart(2, '0');
        let hours = currentDate.getHours().toString().padStart(2, '0');
        let minutes = currentDate.getMinutes().toString().padStart(2, '0');
        let seconds = currentDate.getSeconds().toString().padStart(2, '0');

        return `${year}${month}${day}-${hours}${minutes}${seconds}`;
    }

    return { onRequest };
});

Leave a comment

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