User Event
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
define(['N/redirect'],
(redirect) => {
/**
* 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') {
var recObj = scriptContext.newRecord;
var internalIds = recObj.id;
log.debug('internalIds',internalIds)
var recType = recObj.type;
log.debug('recType',recType)
scriptContext.form.addButton({
id: 'custpage_invoice_print_button',
label: 'Send Barcode Email',
functionName: 'sendBarcodeEmail'
});
scriptContext.form.clientScriptFileId = 461248;
}
}
catch (error) {
log.debug('catchError', error)
}
}
function sendBarcodeEmail(internalIds,recType){
try{
log.debug('in email send button')
redirect.toSuitelet({
scriptId: "customscript_jj_send_email",
deploymentId: "customdeploy_jj_send_email",
parameters:{
internalIds:internalIds,
recType:recType
}
});
}
catch (e) {
log.debug('error@sendBarcodeEmail', error)
}
}
return {beforeLoad,sendBarcodeEmail}
});
Client Script
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
* @NModuleScope SameAccount
*/
define(['N/url','N/currentRecord','N/https','N/ui/message'],
function(url,currentRecord,https,message) {
/**
* 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)
}
function sendBarcodeEmail(){
try{
log.debug('cs starts')
var internalIds = currentRecord.get().id;
var recType = currentRecord.get().type
var currenturl = url.resolveScript({
scriptId: "customscript_jj_send_email",
deploymentId: "customdeploy_jj_send_email",
params:{
internalIds:internalIds,
recType:recType
}
//returnExternalUrl: false
})
var redirectUrl = https.get({
url: currenturl
});
}
}
return {
pageInit: pageInit,
sendBarcodeEmail:sendBarcodeEmail
};
});
Suitelet
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
define(['N/runtime', 'N/search', 'N/record', 'N/encode', 'N/file', 'N/email', 'N/render', 'N/redirect', 'N/ui/message'],
(runtime, search, record, encode, file, email, render, redirect, message) => {
/**
* Defines the Suitelet script trigger point.
* @param {Object} scriptContext
* @param {ServerRequest} scriptContext.request - Incoming request
* @param {ServerResponse} scriptContext.response - Suitelet response
* @since 2015.2
*/
const onRequest = (scriptContext) => {
try {
var request = scriptContext.request;
var response = scriptContext.response;
var recUser = runtime.getCurrentUser().id;
log.debug('recUser', recUser);
var recId = request.parameters.internalIds;
log.debug('recId', recId);
var recType = request.parameters.recType;
log.debug('recType', recType);
var objRecord = record.load({
type: recType,
id: recId,
isDynamic: true,
});
log.debug('objRecord', objRecord);
var custEmail = objRecord.getValue({
fieldId: 'custbody_invoice_email'
});
log.debug('custEmail', custEmail)
var docNo = objRecord.getValue({
fieldId: 'tranid'
});
log.debug('docNo', docNo)
var lineArray = fetchLineLevelData(recId);
log.debug('lineArray', lineArray);
if (lineArray.length > 0) {
var customerID = lineArray[0].customerName
}
var excelData = attachExcel(lineArray, docNo)
log.debug('excelData', excelData);
var customerName = getCustomerName(customerID)
// var fileObj = file.load({
// id: excelData
// });
var myMergeResult = render.mergeEmail({
templateId: 61
});
var emailSubject = myMergeResult.subject;
var emailBody = myMergeResult.body
var custName;
if (customerName.includes(":")) {
var nameArr = customerName.split(":");
var len = nameArr.length;
custName = nameArr[len - 1]
} else {
custName = customerName
}
log.debug('custName', custName)
emailBody = emailBody.replace("CUSTOMER_NAME", custName)
var emailObj = {}
if (custEmail) {
email.send({
author: recUser,
recipients: customerID,
subject: emailSubject,
body: emailBody,
attachments: [excelData],
relatedRecords: {
transactionId: recId
}
});
response.write({output: JSON.stringify("success")})
} else {
emailObj.warningObj = "failed"
response.writeLine({output: JSON.stringify(emailObj)})
}
} catch (e) {
log.debug("error@onRequest", e)
}
}
/**
* @description fetch the data for render as Excel
* @param recID
* @returns {*[]}
*/
function fetchLineLevelData(recID) {
try {
var lineArray = []
var invoiceSearchObj = search.create({
type: "transaction",
filters:
[
["type", "anyof", "SalesOrd", "CustInvc"],
"AND",
["internalid", "anyof", recID],
"AND",
["cogs", "is", "F"],
"AND",
["taxline", "is", "F"],
"AND",
["mainline", "is", "F"],
"AND",
["shipping", "is", "F"]
],
columns:
[
search.createColumn({name: "item", label: "Item"}),
search.createColumn({
name: "upccode",
join: "item",
label: "UPC Code"
}),
search.createColumn({name: "memo", label: "Memo"}),
search.createColumn({
name: "formulanumeric",
formula: "{custcol_pp_unit_conversion}",
label: "Formula (Numeric)"
}),
search.createColumn({name: "rate", label: "Item Rate"}),
search.createColumn({name: "fxrate", label: "Item Rate"}),
search.createColumn({name: "custcol_discount", label: "Discount %"}),
search.createColumn({name: "netamountnotax", label: "Amount (Net of Tax)"}),
// search.createColumn({
// name: "formulacurrency",
// formula: "{netamountnotax}",
// label: "Formula (Currency)"
// }),
search.createColumn({name: "entity", label: "Name"})
]
});
var searchResultCount = invoiceSearchObj.runPaged().count;
log.debug("invoiceSearchObj result count", searchResultCount);
if (searchResultCount > 0) {
invoiceSearchObj.run().each(function (result) {
var itemLineObj = {}
var itemCode = result.getText(invoiceSearchObj.columns[0]);
var itemBarcode = result.getValue(invoiceSearchObj.columns[1]);
var itemDesc = result.getValue(invoiceSearchObj.columns[2]);
var itemQty = result.getValue(invoiceSearchObj.columns[3]);
var itemRate = result.getValue(invoiceSearchObj.columns[5]);
var itemDisc = result.getValue(invoiceSearchObj.columns[6]);
var itemTotal = result.getValue(invoiceSearchObj.columns[7]);
var customerName = result.getValue(invoiceSearchObj.columns[8]);
itemLineObj.itemCode = itemCode
itemLineObj.itemBarcode = itemBarcode
itemLineObj.itemDesc = itemDesc
itemLineObj.itemQty = itemQty
itemLineObj.itemRate = itemRate
itemLineObj.itemDisc = itemDisc
itemLineObj.itemTotal = parseFloat(itemTotal);
itemLineObj.customerName = customerName
lineArray.push(itemLineObj)
return true;
});
}
return lineArray
} catch (e) {
log.debug("error@fetchLineLevelData", e)
}
}
/**
* @description create Excel with given data from current record(SO or Invoice)
* @param lineArray
* @param docNo
* @returns {File}
*/
function attachExcel(lineArray, docNo) {
try {
log.debug('in attachExcel1');
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="Customer Statement"> ' +
'<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">Item_Code</Data></Cell> ' +
'<Cell ss:Index="2" ss:StyleID="s72"><Data ss:Type="String">Barcode</Data></Cell> ' +
'<Cell ss:Index="3" ss:StyleID="s72"><Data ss:Type="String">Description</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">Unit Price</Data></Cell> ' +
'<Cell ss:Index="6" ss:StyleID="s72"><Data ss:Type="String">Discount%</Data></Cell> ' +
'<Cell ss:Index="7" ss:StyleID="s72"><Data ss:Type="String">Total $</Data></Cell> ' +
'</Row> ';
for (var itemRow = 0; itemRow < lineArray.length; itemRow++) {
XML += '<Row ss:AutoFitHeight="0" ss:Height="13">'
+ '<Cell ss:Index="1" ss:StyleID="s72"><Data ss:Type="String">' + lineArray[itemRow].itemCode + '</Data></Cell>'
+ '<Cell ss:Index="2" ss:StyleID="s72"><Data ss:Type="String">' + lineArray[itemRow].itemBarcode + '</Data></Cell>'
+ '<Cell ss:Index="3" ss:StyleID="s72"><Data ss:Type="String">' + lineArray[itemRow].itemDesc + '</Data></Cell>'
+ '<Cell ss:Index="4" ss:StyleID="s73"><Data ss:Type="String">' + lineArray[itemRow].itemQty + '</Data></Cell>'
+ '<Cell ss:Index="5" ss:StyleID="s73"><Data ss:Type="String">' + lineArray[itemRow].itemRate + '</Data></Cell>'
+ '<Cell ss:Index="6" ss:StyleID="s72"><Data ss:Type="String">' + lineArray[itemRow].itemDisc + '</Data></Cell>'
+ '<Cell ss:Index="7" ss:StyleID="s73"><Data ss:Type="String">' + lineArray[itemRow].itemTotal + '</Data></Cell>'
+ '</Row>';
}
XML = XML + '</Table><WorksheetOptions/> </Worksheet></Workbook>';
var strXmlEncoded = encode.convert({
string: XML,
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64
});
var objXlsFile = file.create({
name: docNo + '.xls',
fileType: file.Type.EXCEL,
//folder:100189,
contents: strXmlEncoded
});
log.debug('objXlsFile', objXlsFile);
//objXlsFile.folder = 100189;
// var fileId = objXlsFile.save()
//log.debug('fileId',fileId)
return objXlsFile;
} catch (e) {
log.debug({
title: e.name,
details: e
});
}
}
/**
* @description fetch the current record(SO or Invoice)customer id and name
* @param customerId
* @returns {*}
*/
function getCustomerName(customerId) {
try {
var customerSearchObj = search.create({
type: "customer",
filters:
[
["internalid", "anyof", customerId]
],
columns:
[
search.createColumn({
name: "entityid",
sort: search.Sort.ASC,
label: "ID"
}),
search.createColumn({name: "altname", label: "Name"}),
]
});
var searchResultCount = customerSearchObj.runPaged().count;
log.debug("customerSearchObj result count", searchResultCount);
var customerName;
if (searchResultCount > 0) {
customerSearchObj.run().each(function (result) {
customerName = result.getValue(customerSearchObj.columns[1]);
return true;
});
}
return customerName;
} catch (e) {
}
}
return {onRequest}
});