Send PO details in Excel Format to SFTP Server

User event script is used to store the PO details in file cabinet and send it to SFTP server in Excel format.

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
define(['N/file', 'N/record', 'N/search', 'N/sftp', 'N/encode'],
    /**
 * @param{file} file
 * @param{record} record
 * @param{search} search
 * @param{sftp} sftp
 */
    (file, record, search, sftp,encode) => {

        function getOrderData(salesOrderId) {
            try{
                var orderDetails = '';

                log.debug('salesOrderId',salesOrderId)

                var salesorderSearchObj = search.create({
                    type: "salesorder",
                    filters:
                        [
                            ["type","anyof","SalesOrd"],
                            "AND",
                            ["item.isdropshipitem","is","T"],
                            "AND",
                            ["internalid","anyof",salesOrderId]
                        ],
                    columns:
                        [
                            search.createColumn({name: "internalid", label: "Internal ID"}),
                            search.createColumn({name: "otherrefnum", label: "PO/Cheque Number"}),
                            search.createColumn({name: "datecreated", label: "Date Created"}),
                            search.createColumn({name: "entity", label: "Name"}),
                            search.createColumn({name: "shipaddress1", label: "Shipping Address 1"}),
                            search.createColumn({name: "shipaddress2", label: "Shipping Address 2"}),
                            search.createColumn({name: "shipaddress3", label: "Shipping Address 3"}),
                            search.createColumn({name: "shipcity", label: "Shipping City"}),
                            search.createColumn({name: "shipcountry", label: "Shipping Country"}),
                            search.createColumn({name: "shipzip", label: "Shipping Zip"}),
                            search.createColumn({name: "shipphone", label: "Shipping Phone"}),
                            search.createColumn({name: "email", label: "Email"}),
                            search.createColumn({name: "memomain", label: "Memo"}),
                            search.createColumn({name: "quantity", label: "Quantity"}),
                            search.createColumn({
                                name: "mpn",
                                join: "item",
                                label: "MPN"
                            }),
                            //  search.createColumn({name: "paymentoption", label: "Payment Option"})
                        ]
                });
                var searchResultCount = salesorderSearchObj.runPaged().count;
                log.debug("salesorderSearchObj result count",searchResultCount);
                return salesorderSearchObj;

            }catch(error){
                log.error("Error @getOrderData",error);
                return '';
            }
        }

        function createCSVFileRequest(poid,results){
            try{
                // var myContent;
                var columns = results.columns;
                var content = new Array();
                var headers = new Array();
                var temp = new Array();
                var x = 0
                results.run().each(function (result) {
                    content[x] = "";

                    var internalid= result.getValue(result.columns[0]);
                    var otherrefnum= result.getValue(result.columns[1]);
                    var datecreated= result.getValue(result.columns[2]);
                    var entity= result.getText(result.columns[3]);
                    var shipaddress1= result.getValue(result.columns[4]);
                    var shipaddress2= result.getValue(result.columns[5]);
                    var shipaddress3= result.getValue(result.columns[6]);
                    var shipcity= result.getValue(result.columns[7]);
                    var shipcountry= result.getText(result.columns[8]);
                    var shipzip= result.getValue(result.columns[9]);
                    var shipphone= result.getValue(result.columns[10]);
                    var email= result.getValue(result.columns[11]);
                    var memo= result.getValue(result.columns[12]);
                    var quantity= result.getValue(result.columns[13]);
                    var mpn= result.getValue(result.columns[14]);

                    temp.push('"'+internalid+'"')
                    temp.push('"'+otherrefnum+'"');
                    temp.push('"'+datecreated+'"');
                    temp.push('"'+entity+'"');
                    temp.push('"'+shipaddress1+'"');
                    temp.push('"'+shipaddress2+'"');
                    temp.push('"'+shipaddress3+'"');
                    temp.push('"'+shipcity+'"');
                    temp.push('"'+shipcountry+'"');
                    temp.push('"'+shipzip+'"');
                    temp.push('"'+shipphone+'"');
                    temp.push('"'+email+'"');
                    temp.push('"'+memo+'"');
                    temp.push('"'+quantity+'"');
                    temp.push('"'+mpn+'"');
                    content[x] += temp;
                    log.debug("temp", temp);
                    log.debug("content[x]", content[x]);
                    x++;
                    log.debug("x",x);
                    return true;
                });
                var contents = '';
                for (var z = 0; z < content.length; z++) {
                    contents += content[z].toString() + '\n';
                }
                log.debug("contents",contents);

                let fileObj = file.create({
                    name: 'Maze-stock of ' + poid+'.csv',
                    fileType: file.Type.CSV,
                    contents: contents,
                    folder: '1886'//Netsuite-Maze Dropship Orders
                });
                let fileId = fileObj.save();
                log.debug('fileId',fileId)
                return {fileId: fileId,fileObj: fileObj};
                //}
            }catch(error){
                log.error("Error @createCSVFileRequest",error);
            }
        }
        function uploadFileToServer(fileObj){
            try{

                const myPwdGuid = "e21d84c31ebd4bb897a5b2930c90136a";
                const myHostKey = "AAAAB3NzaC1yc2EAAAADAQABAAABAQDW5s75gHDWU9IGQTKpBe3XTEh6ISYz/8cRlPpoIR+3J7BoMMTInx9v2MAbERMV+gWSW8qWAQOoC3VnF3wnNQXvsJgeINsvnRjG50FpAbzq9FAUzPxyxNBgLGQuBs1YCb12u+vI77FpnXeI1RPvuz7cHq1MGoIz5YUYT9EIZBmkrVsrKL3sEW6sacNdjW7w+O/OpzBQpM87A+K6hgGcV5vJCWoQO4ghacO7LolEebDYMv3PnWK6bVgMcGYFCdN2haK0/8TwRl242eLMv59R1AWUmB7qSW4b/OlIv2UeTRsOQhZY4lNcz7KvfgxKtX+xd6IPufkRf+OXxMmpj8IpkebH";

                // Establish a connection to a remote SFTP server
                let connection = sftp.createConnection({
                    username: 'MazeUser',
                    passwordGuid: myPwdGuid,
                    url: 's-7e1df0f0dc9148c9a.server.transfer.eu-west-2.amazonaws.com',
                    hostKey: myHostKey,
                    directory:'/maze-hl-bucket/Order Waiting to Import'
                });
                log.debug('connection',connection)
                // Upload the file to the remote server
                try{
                    fileObj && connection.upload({
                        // directory: '/maze-hl-bucket/Order Waiting to Import',
                        // filename: 'Maze-Stock of ' + internalID + '.csv',
                        file: fileObj,
                        replaceExisting: true
                    });
                }catch(e){
                    log.debug("error @connection upload",e);
                }
            }catch(error){
                log.error("Error @UploadFileToServer",error);
            }
        }
        /**
         * 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) => {

        }

        /**
         * Defines the function definition that is executed before 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 beforeSubmit = (scriptContext) => {

        }

        /**
         * 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) => {
           log.debug("scriptContext.type", scriptContext.type);
            var salesOrderId = scriptContext.newRecord.getValue('createdfrom');
            log.debug("inside afterSubmit dropship", salesOrderId);

            const poRecord = scriptContext.newRecord;
            const poid = poRecord.id;
            let vendor = poRecord.getValue({
                fieldId: 'entity'
            });
            log.debug("vendor", vendor);
            let soId = poRecord.getValue({
                fieldId: 'createdfrom'
            });
            log.debug('soId',soId);
            // let soNum = poRecord.getText({
            //     fieldId: 'createdfrom'
            // });
            // log.debug('soNum',soNum);
            // let soArr=soNum.split('#')
            // var soType=soArr[0].toString().trim();
            // log.debug('soType',soType);
           // var field= search.lookupFields({type:'purchaseorder',id:soId,columns:['createdfrom.type']});
           // log.debug('field',field);
             if (/*((scriptContext.type == 'dropship' ||(scriptContext.type == 'create' && soId)) && vendor == '653')*/ /* Vendor: VEN_0187 Maze Rattan Limited *//*|| */((scriptContext.type == 'dropship' ||(scriptContext.type == 'create' && soId)) && vendor == '834')) {
           // if (scriptContext.type == 'edit' && vendor == '834') {
                let orderDetails = getOrderData(salesOrderId);
                log.debug("orderDetails", orderDetails);
                if (orderDetails) {
                    let file = createCSVFileRequest(poid, orderDetails);
                    log.debug("File", file);
                    // file &&  uploadFileToServer(file.fileObj);
                }
            }
            // Pacific Lifestyle Integration Part
            if ((scriptContext.type == 'dropship' ||(scriptContext.type == 'create' && soId)) && vendor == '834') {//65249  65249
             //   if (((scriptContext.type == 'edit'||(scriptContext.type == 'create' && soId)) && vendor == '834')) {
                log.debug("inside condition", true);

                let pacificOrderDetails = getPacificOrderData(poid);
                log.debug("orderDetails", pacificOrderDetails);
                if (pacificOrderDetails) {
                    let pacificFile = createPacificCSVFileRequest(poid,pacificOrderDetails);
                    log.debug("File", pacificFile);
                    pacificFile &&  pacificuploadFileToServer(pacificFile.fileObj);
                }
            }

        }
        function getPacificOrderData(poid) {
            try{
                var orderDetails = '';

                var purchaseorderSearchObj = search.create({
                    type: "purchaseorder",
                    filters:
                        [
                            ["type","anyof","PurchOrd"],
                            "AND",
                            ["item.isdropshipitem","is","T"],
                            "AND",
                            ["internalid","anyof",poid]
                        ],
                    columns:
                        [
                            search.createColumn({name: "tranid", label: "Document Number"}),
                            search.createColumn({
                                name: "formulatext",
                                formula: "'HARB004'",
                                label: "Customer Account No"
                            }),
                            search.createColumn({name: "item", label: "Item"}),
                            search.createColumn({name: "quantity", label: "Quantity"}),
                            search.createColumn({
                                name: "altname",
                                join: "customer",
                                label: "Name"
                            }),
                            search.createColumn({name: "shipaddress1", label: "Shipping Address 1"}),
                            search.createColumn({name: "shipaddress2", label: "Shipping Address 2"}),
                            search.createColumn({name: "shipaddress3", label: "Shipping Address 3"}),
                            search.createColumn({name: "shipcity", label: "Shipping City"}),
                            search.createColumn({name: "shipcountry", label: "Shipping Country"}),
                            search.createColumn({name: "shipzip", label: "Shipping Zip"}),
                            search.createColumn({name: "shipphone", label: "Shipping Phone"}),
                            search.createColumn({
                                name: "formulatext",
                                formula: "TO_CHAR({trandate}, 'DD/MM/YYYY')",
                                label: "Formula (Text)"
                            }),
                            search.createColumn({
                                name: "formulatext",
                                formula: "CASE TO_CHAR({trandate} + 3, 'D') WHEN '1' THEN TO_CHAR({trandate} + 5, 'DD/MM/YYYY') WHEN '7' THEN TO_CHAR({trandate} + 5, 'DD/MM/YYYY') ELSE TO_CHAR({trandate} + 3, 'DD/MM/YYYY') END",
                                label: "Formula (Text)"
                            }),
                            search.createColumn({
                                name: "otherrefnum",
                                join: "createdFrom",
                                label: "PO/Cheque Number"
                            })
                        ]
                });
                var searchResultCount = purchaseorderSearchObj.runPaged().count;
                log.debug("purchaseorderSearchObj result count",searchResultCount);
                return purchaseorderSearchObj;



            }
            catch(error){
                log.error("Error @getOrderData",error);
                return '';
            }
        }
        function getPacificOrderData(poid) {
            try{
                var orderDetails = '';

                var purchaseorderSearchObj = search.create({
                    type: "purchaseorder",
                    filters:
                        [
                            ["type","anyof","PurchOrd"],
                            "AND",
                            ["item.isdropshipitem","is","T"],
                            "AND",
                            ["internalid","anyof",poid]
                        ],
                    columns:
                        [
                            search.createColumn({name: "tranid", label: "Document Number"}),
                            search.createColumn({
                                name: "formulatext1",
                                formula: "'HARB004'",
                                label: "Customer Account No"
                            }),
                            search.createColumn({name: "item", label: "Item"}),
                            search.createColumn({name: "quantity", label: "Quantity"}),
                            search.createColumn({
                                name: "altname",
                                join: "customer",
                                label: "Name"
                            }),
                            search.createColumn({name: "shipaddress1", label: "Shipping Address 1"}),
                            search.createColumn({name: "shipaddress2", label: "Shipping Address 2"}),
                            search.createColumn({name: "shipaddress3", label: "Shipping Address 3"}),
                            search.createColumn({name: "shipcity", label: "Shipping City"}),
                            search.createColumn({name: "shipcountry", label: "Shipping Country"}),
                            search.createColumn({name: "shipzip", label: "Shipping Zip"}),
                            search.createColumn({name: "shipphone", label: "Shipping Phone"}),
                            search.createColumn({
                                name: "formulatext2",
                                formula: "TO_CHAR({trandate}, 'DD/MM/YYYY')",
                                label: "Formula (Text)"
                            }),
                            search.createColumn({
                                name: "formulatext3",
                                formula: "CASE TO_CHAR({trandate} + 3, 'D') WHEN '1' THEN TO_CHAR({trandate} + 5, 'DD/MM/YYYY') WHEN '7' THEN TO_CHAR({trandate} + 5, 'DD/MM/YYYY') ELSE TO_CHAR({trandate} + 3, 'DD/MM/YYYY') END",
                                label: "Formula (Text)"
                            }),
                            search.createColumn({
                                name: "otherrefnum",
                                join: "createdFrom",
                                label: "PO/Cheque Number"
                            })
                        ]
                });
                var searchResultCount = purchaseorderSearchObj.runPaged().count;

                log.debug("purchaseorderSearchObj result count",searchResultCount);
                var poArray = [];

                purchaseorderSearchObj.run().each(function (result) {
                    var poObj = {};
                    // poObj.itemname = escapeXml(result.getText({
                    // {name: "tranid", label: "Document Number"}
                    // }));
                    poObj.internalId = result.getValue({
                        name: "tranid",
                        label: "Document Number"
                    });
                    poObj.accountNo = result.getValue({
                        name: "formulatext1",
                        formula: "'HARB004'",
                        label: "Customer Account No"
                    });
                    poObj.item = escapeXml(result.getText({
                        name: "item",
                        label: "Item"
                    }));
                    poObj.quantity = result.getValue({
                        name: "quantity",
                        label: "Quantity"
                    });
                    poObj.entity = result.getValue({
                        name: "altname",
                        join: "customer",
                        label: "Name"
                    });
                    poObj.shipaddr1 = result.getValue({
                        name: "shipaddress1",
                        label: "Shipping Address 1"
                    });
                    poObj.shipaddr2 = result.getValue({
                        name: "shipaddress2",
                        label: "Shipping Address 2"
                    });
                    poObj.shipaddr3 = result.getValue({
                        name: "shipaddress3",
                        label: "Shipping Address 3"
                    });
                    poObj.shipCity = result.getValue({
                        name: "shipcity",
                        label: "Shipping City"
                    });
                    poObj.shipCountry = result.getText({
                        name: "shipcountry",
                        label: "Shipping Country"
                    });
                    poObj.zip = result.getValue({
                        name: "shipzip",
                        label: "Shipping Zip"
                    });
                    poObj.phone = result.getValue({
                        name: "shipphone",
                        label: "Shipping Phone"
                    });
                    poObj.trandate = result.getValue({
                        name: "formulatext2",
                        formula: "TO_CHAR({trandate}, 'DD/MM/YYYY')",
                        label: "Formula (Text)"
                    });
                    poObj.promiseDate = result.getValue({
                        name: "formulatext3",
                        formula: "CASE TO_CHAR({trandate} + 3, 'D') WHEN '1' THEN TO_CHAR({trandate} + 5, 'DD/MM/YYYY') WHEN '7' THEN TO_CHAR({trandate} + 5, 'DD/MM/YYYY') ELSE TO_CHAR({trandate} + 3, 'DD/MM/YYYY') END",
                        label: "Formula (Text)"
                    });
                    poObj.orderNo = result.getValue({
                        name: "otherrefnum",
                        join: "createdFrom",
                        label: "PO/Cheque Number"
                    });
                    poArray.push(poObj);
                    return true;
                });

                return poArray;


            }
            catch(error){
                log.error("Error @getOrderData",error);
                return '';
            }
        }
        function escapeXml(param) {
            try {
                return param.replace(/[<>&'"]/g, function (c) {
                    switch (c) {
                        case '<':
                            return '&lt;';
                        case '>':
                            return '&gt;';
                        case '&':
                            return '&amp;';
                        case '\'':
                            return '&apos;';
                        case '"':
                            return '&quot;';
                    }
                });
            } catch (e) {
                log.debug("Error@escapeXml", e);
            }
        }
        function createPacificCSVFileRequest(poid,results){
            try {

                var excelArr = []
                var XML = '';

                XML = XML + '<?xml version="1.0"?> <?mso-application progid="Excel.Sheet"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">'
                XML = XML + '<Styles><Style ss:ID="Default" ss:Name="Normal"><Alignment ss:Vertical="Bottom"/><Borders/><Font ss:FontName="Arial" x:CharSet="204" ss:Color="#000000"/><Interior/><NumberFormat/><Protection/></Style><Style ss:ID="s62"><Alignment ss:Horizontal="Left" ss:Vertical="Top"/><Borders/><Interior/></Style><Style ss:ID="s72"><Alignment ss:Horizontal="Left" ss:Vertical="Top"/><Borders/><Font ss:FontName="Arial" x:Family="Roman" ss:Size="10" ss:Color="#000000"/><Interior/></Style><Style ss:ID="s73"><Alignment ss:Horizontal="Right" ss:Vertical="Top"/><Borders/><Font ss:FontName="Arial" x:Family="Roman" ss:Size="10" ss:Color="#000000"/><Interior/></Style></Styles>';
                XML = XML + '<Worksheet ss:Name="Purchase Order"> ' +
                    '<Table ss:ExpandedColumnCount="100" ss:ExpandedRowCount="7000" x:FullColumns="1" x:FullRows="1" ss:StyleID="s62" ss:DefaultColumnWidth="40.5"> <Column ss:StyleID="s62" ss:AutoFitWidth="0" ss:Width="58.5"/> ' +
                    '<Row ss:AutoFitHeight="0" ss:Height="13"> ' +
                    '<Cell ss:Index="1"  ss:StyleID="s72"><Data ss:Type="String">PO Number</Data></Cell> ' +
                    '<Cell ss:Index="2"  ss:StyleID="s72"><Data ss:Type="String">Customer Acc No</Data></Cell> ' +
                    '<Cell ss:Index="3"  ss:StyleID="s72"><Data ss:Type="String">Part Number</Data></Cell> ' +
                    '<Cell ss:Index="4"  ss:StyleID="s72"><Data ss:Type="String">Quantity</Data></Cell> ' +
                    '<Cell ss:Index="5"  ss:StyleID="s72"><Data ss:Type="String">Customer Name</Data></Cell> ' +
                    '<Cell ss:Index="6"  ss:StyleID="s72"><Data ss:Type="String">Delivery Address 1</Data></Cell> ' +
                    '<Cell ss:Index="7"  ss:StyleID="s72"><Data ss:Type="String">Delivery Address 2</Data></Cell> ' +
                    '<Cell ss:Index="8"  ss:StyleID="s72"><Data ss:Type="String">Delivery Address 2</Data></Cell> ' +
                    '<Cell ss:Index="9"  ss:StyleID="s72"><Data ss:Type="String">Delivery Town</Data></Cell> ' +
                    '<Cell ss:Index="10"  ss:StyleID="s72"><Data ss:Type="String">Delivery Country</Data></Cell> ' +
                    '<Cell ss:Index="11"  ss:StyleID="s72"><Data ss:Type="String">Delivery Post Code</Data></Cell> ' +
                    '<Cell ss:Index="12"  ss:StyleID="s72"><Data ss:Type="String">Telephone Number</Data></Cell> ' +
                    '<Cell ss:Index="13"  ss:StyleID="s72"><Data ss:Type="String">Order Date</Data></Cell> ' +
                    '<Cell ss:Index="14"  ss:StyleID="s72"><Data ss:Type="String">Promised Date</Data></Cell> ' +
                    '<Cell ss:Index="15"  ss:StyleID="s72"><Data ss:Type="String">Order Number</Data></Cell> ' +
                    '</Row> ';
                for (var itemRow = 0; itemRow < results.length; itemRow++) {

                    XML += '<Row ss:AutoFitHeight="0" ss:Height="13">'
                        + '<Cell ss:Index="1"  ss:StyleID="s72"><Data ss:Type="String">' + results[itemRow].internalId + '</Data></Cell>'
                        + '<Cell ss:Index="2"  ss:StyleID="s72"><Data ss:Type="String">' + results[itemRow].accountNo + '</Data></Cell>'
                        + '<Cell ss:Index="3"  ss:StyleID="s72"><Data ss:Type="String">' + results[itemRow].item + '</Data></Cell>'
                        + '<Cell ss:Index="4"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].quantity + '</Data></Cell>'
                        + '<Cell ss:Index="5"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].entity + '</Data></Cell>'
                        + '<Cell ss:Index="6"  ss:StyleID="s72"><Data ss:Type="String">' + results[itemRow].shipaddr1 + '</Data></Cell>'

                    //  if(itemRow == 0){
                    XML += '<Cell ss:Index="7"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].shipaddr2 + '</Data></Cell>'
                        + '<Cell ss:Index="8"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].shipaddr3 + '</Data></Cell>'
                        + '<Cell ss:Index="9"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].shipCity + '</Data></Cell>'
                        + '<Cell ss:Index="10"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].shipCountry + '</Data></Cell>'
                        + '<Cell ss:Index="11"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].zip + '</Data></Cell>'
                        + '<Cell ss:Index="12"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].phone + '</Data></Cell>'
                        + '<Cell ss:Index="13"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].trandate + '</Data></Cell>'
                        + '<Cell ss:Index="14"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].promiseDate + '</Data></Cell>'
                        + '<Cell ss:Index="15"  ss:StyleID="s73"><Data ss:Type="String">' + results[itemRow].orderNo + '</Data></Cell>'
                    //    }

                    XML += '</Row>';
                }
                XML = XML + '</Table> </Worksheet></Workbook>';
                var strXmlEncoded = encode.convert({
                    string: XML,
                    inputEncoding: encode.Encoding.UTF_8,
                    outputEncoding: encode.Encoding.BASE_64
                });
                var objXlsFile = file.create({
                    name: 'Pacific-Order of ' + poid+'.xlsx',
                    fileType: file.Type.EXCEL,
                    folder:'7459',
                    contents: strXmlEncoded

                });
                log.debug('objXlsFile', objXlsFile);
                let fileId = objXlsFile.save();
                log.debug('fileId',fileId)
                return {fileId: fileId,objXlsFile: objXlsFile};


                // return objXlsFile;

            } catch (e) {
                log.debug({
                    title: e.name,
                    details: e
                });
            }
        }
        function pacificuploadFileToServer(fileObj){
            try{

                const myPwdGuid = "e21d84c31ebd4bb897a5b2930c90136a";
                const myHostKey = "AAAAB3NzaC1yc2EAAAADAQABAAABAQDW5s75gHDWU9IGQTKpBe3XTEh6ISYz/8cRlPpoIR+3J7BoMMTInx9v2MAbERMV+gWSW8qWAQOoC3VnF3wnNQXvsJgeINsvnRjG50FpAbzq9FAUzPxyxNBgLGQuBs1YCb12u+vI77FpnXeI1RPvuz7cHq1MGoIz5YUYT9EIZBmkrVsrKL3sEW6sacNdjW7w+O/OpzBQpM87A+K6hgGcV5vJCWoQO4ghacO7LolEebDYMv3PnWK6bVgMcGYFCdN2haK0/8TwRl242eLMv59R1AWUmB7qSW4b/OlIv2UeTRsOQhZY4lNcz7KvfgxKtX+xd6IPufkRf+OXxMmpj8IpkebH";
                log.debug('myPwdGuid',myPwdGuid)
                // Establish a connection to a remote SFTP server
                let connection = sftp.createConnection({
                    username: 'MazeUser',
                    passwordGuid: myPwdGuid,
                    url: 's-7e1df0f0dc9148c9a.server.transfer.eu-west-2.amazonaws.com',
                    hostKey: myHostKey,
                    directory:'/maze-hl-bucket/Pacific-Order Waiting to Export'
                });
                log.debug('connection',connection)
                // Upload the file to the remote server
                try{
                    fileObj && connection.upload({
                        // directory: '/maze-hl-bucket/Order Waiting to Import',
                        // filename: 'Maze-Stock of ' + internalID + '.csv',
                        file: fileObj,
                        replaceExisting: true
                    });
                }catch(e){
                    log.debug("error @connection upload",e);
                }
            }catch(error){
                log.error("Error @UploadFileToServer",error);
            }
        }

        return {beforeLoad, beforeSubmit, afterSubmit}

    });

Leave a comment

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