/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
define([‘N/log’, ‘N/search’, ‘N/ui/serverWidget’],
/**
* @param {import(“N/log”)} log
* @param {import(“N/search”)} search
* @param {import(“N/ui/serverWidget”)} serverWidget
*/
(log, search, serverWidget) => {
/**
* Function executed upon sending a request to the Suitelet.
* @param {Object} scriptContext The context of the Suitelet script
* @param {ServerRequest} scriptContext.request – Encapsulation of the incoming request
* @param {ServerResponse} scriptContext.response – Encapsulation of the Suitelet response
* @returns {Object} Suitelet onRequest function
*/
const onRequest = (scriptContext) => {
try {
const pageSize = 25; // Number of items per page
let pageIndex = parseInt(scriptContext.request.parameters.pageIndex) || 0; // Current page index
// Create a form
let form = serverWidget.createForm({
title: ‘Items Purchased Form’
});
form.clientScriptFileId = 2165311;
// Add field group for totals and page index
let fieldGroup = form.addFieldGroup({
id: ‘totals_page_group’,
label: ‘ ‘
});
// Add sublist to the form
let sublist = form.addSublist({
id: ‘custpage_items_purchased’,
label: ‘Items Purchased’,
type: serverWidget.SublistType.LIST
});
// Add fields to the sublist
sublist.addField({
id: ‘item’,
label: ‘Item’,
type: serverWidget.FieldType.TEXT
});
sublist.addField({
id: ‘description’,
label: ‘Description’,
type: serverWidget.FieldType.TEXT
});
sublist.addField({
id: ‘quantity’,
label: ‘Quantity’,
type: serverWidget.FieldType.INTEGER
});
sublist.addField({
id: ‘amount’,
label: ‘Total’,
type: serverWidget.FieldType.CURRENCY
});
sublist.addField({
id: ‘unitpriceavg’,
label: ‘Unit Price (Average)’,
type: serverWidget.FieldType.CURRENCY
});
sublist.addField({
id: ‘lastpurchasedate’,
label: ‘Last Purchase Date’,
type: serverWidget.FieldType.DATE
});
// Get the customer record ID from the Suitelet parameters
let customerId = scriptContext.request.parameters.customerId;
let customerName = scriptContext.request.parameters.customerName;
form.addField({
id: ‘custpage_customer_id’,
type: serverWidget.FieldType.TEXT,
label: ‘Customer ID’,
}).updateDisplayType({
displayType: serverWidget.FieldDisplayType.HIDDEN
}).defaultValue = customerId;
form.addField({
id: ‘custpage_customer_name’,
type: serverWidget.FieldType.INLINEHTML,
label: ‘Customer Name’,
container: ‘totals_page_group’
// }).updateDisplayType({
//displayType: serverWidget.FieldDisplayType.DISABLED
}).defaultValue = ‘<div style=”font-size: 16px;”><b>’ + customerName + ‘</b></div>’;
// Execute the saved search
let transactionSearchObj = search.create({
type: “transaction”,
filters: [
[“type”, “anyof”, “CashRfnd”, “CashSale”, “CustCred”, “CustChrg”, “CustInvc”],
“AND”,
[“item.type”, “anyof”, “Service”, “OthCharge”, “NonInvtPart”, “Kit”, “Assembly”, “InvtPart”],
“AND”,
[“accounttype”, “anyof”, “Income”, “DeferRevenue”],
“AND”,
[“customermain.internalid”, “anyof”, customerId],
“AND”,
[“customer.isinactive”, “is”, “F”] // Exclude inactive customers
],
columns: [
search.createColumn({
name: “itemid”,
join: “item”,
summary: “GROUP”,
label: “Item”,
sort: search.Sort.ASC
}),
search.createColumn({
name: “salesdescription”,
join: “item”,
summary: “MIN”,
label: “Description”
}),
search.createColumn({
name: “quantity”,
summary: “SUM”,
label: “Quantity”
}),
search.createColumn({
name: “netamount”,
summary: “SUM”,
label: “Total”
}),
search.createColumn({
name: “effectiverate”,
summary: “AVG”,
label: “Unit Price (Average)”
}),
search.createColumn({
name: “trandate”,
summary: “MAX”,
label: “Last Purchase Date”
})
]
});
// Paginate search results
let pagedData = transactionSearchObj.runPaged({ pageSize: pageSize });
let totalLines = pagedData.count;
let totalPages = Math.ceil(totalLines / pageSize);
if (totalLines === 0) {
// If there are no search results, display a message
form.addField({
id: ‘no_purchases_message’,
type: serverWidget.FieldType.INLINEHTML,
label: ‘No Purchases’,
container: ‘custpage_items_purchased’
})
} else {
// Set page index from request parameters or default to 0 if out of range
if (pageIndex < 0 || pageIndex >= totalPages) {
pageIndex = 0;
}
// Get the search results for the current page
let currentPage = pagedData.fetch({ index: pageIndex });
let lineCount = 0; // Initialize line count
// Initialize total quantity and total amount for all search results
let totalQuantity = 0;
let totalAmount = 0;
currentPage.data.forEach(function (result) {
sublist.setSublistValue({
id: ‘item’,
line: lineCount,
value: result.getValue({ name: ‘itemid’, join: ‘item’, summary: ‘GROUP’ })
});
sublist.setSublistValue({
id: ‘description’,
line: lineCount,
value: result.getValue({ name: ‘salesdescription’, join: ‘item’, summary: ‘MIN’ })
});
sublist.setSublistValue({
id: ‘quantity’,
line: lineCount,
value: result.getValue({ name: ‘quantity’, summary: ‘SUM’ })
});
sublist.setSublistValue({
id: ‘amount’,
line: lineCount,
value: result.getValue({ name: ‘netamount’, summary: ‘SUM’ })
});
sublist.setSublistValue({
id: ‘unitpriceavg’,
line: lineCount,
value: result.getValue({ name: ‘effectiverate’, summary: ‘AVG’ })
});
const trandateValue = result.getValue({ name: ‘trandate’, summary: ‘MAX’ });
sublist.setSublistValue({
id: ‘lastpurchasedate’,
line: lineCount,
value: trandateValue
});
// Increment line count for each line processed
lineCount++;
});
// Calculate total quantity and total amount from all search results
transactionSearchObj.run().each(function (result) {
totalQuantity += parseInt(result.getValue({ name: ‘quantity’, summary: ‘SUM’ }));
totalAmount += parseFloat(result.getValue({ name: ‘netamount’, summary: ‘SUM’ }));
return true; // Continue processing additional results
});
let pageSelectField = form.addField({
id: ‘custpage_page_index’,
type: serverWidget.FieldType.SELECT,
label: ‘Line Index’,
container: ‘totals_page_group’
});
// Add summary box
let summaryValue = setSummaryBox({ totalQuantity: totalQuantity, totalAmount: totalAmount });
let summaryField = form.addField({
id: ‘custpage_filter_summary’,
label: ‘Summary’,
type: serverWidget.FieldType.INLINEHTML,
container: ‘totals_page_group’,
});
summaryField.defaultValue = summaryValue;
for (let i = 0; i < totalPages; i++) {
let startIndex = (i * pageSize) + 1;
let endIndex = Math.min((i + 1) * pageSize, totalLines);
pageSelectField.addSelectOption({
value: i.toString(),
text: startIndex + ‘-‘ + endIndex + ‘ of ‘ + totalLines,
isSelected: (i === pageIndex)
});
}
}
// Render the form
scriptContext.response.writePage(form);
} catch (e) {
log.error(‘Error’, e.message);
}
}
/**
* Function to set the summary box
* @param {*} summaryLine – object containing summary box details
* @returns {*} html
*/
function setSummaryBox(summaryLine) {
let html = ‘<style>’ +
‘table.newtotallingtable caption {n‘ +
‘ display: table-caption !important;n‘ +
‘ margin-bottom: 10px;n‘ +
‘ font-weight: bold;n‘ +
‘ color: white;n‘ +
‘ font-size: 12px !important;n‘ +
‘ padding: 4px 0px 4px 8px;n‘ +
‘}’ +
‘table.newtotallingtable caption {n‘ +
‘ background-color: #607799;n‘ +
‘}’ +
‘caption, th {n‘ +
‘ text-align: left;n‘ +
‘}’ +
‘</style>’;
html += ‘<div style=”text-align: right; padding-right: 20px;”>’;
html += ‘<span class=”bgmd totallingbg” style=”display:inline-block; padding: 10px 25px; margin-bottom:5px;”>’;
html += ‘<table class=”newtotallingtable” cellspacing=”2? cellpadding=”0px” border=”0px” style=”padding: 5px;n‘ +
‘ width: 217px;”><caption style=”display: none;” >Summary</caption><tbody><td style=”text-align: left;”>’; // Adjusted alignment
html += ‘<div class=”uir-field-wrapper” data-field-type=”currency”><span id=”subtotal_fs_lbl_uir_label” class=”smalltextnolink uir-label “><span id=”subtotal_fs_lbl” class=”smalltextnolink” style=”color: #262626 !important; font-size: 12px; padding-bottom:10px;”>’
html += ‘Total Quantity</td>’;
html += ‘<td style=”text-align: right; color: #262626 !important; font-size: 13px; padding-bottom:10px;” align=”right” id=”subtotal”><b>’; // Adjusted alignment
html += summaryLine.totalQuantity + ‘</b></td><td></td></tr>’;
html += ‘<tr><td style=”text-align: left; color: #262626 !important; font-size: 12px;”>TOTAL AMOUNT</td><td align=”right” style=”font-size: 13px; color: #262626 !important;”><b>’;
html += ‘<span style=”font-size: 13px; color: #262626; padding-left: 2px;”>’ + summaryLine.totalAmount.toFixed(2) + ‘</span></b></td></tr>’; // Adjusted alignment
html += ‘</table></div>’;
return html;
}
return { onRequest };
});