View Task : GGBN-236
HTML
<html>
<body>
<div id="alertMessage" class="alert alert-danger" style="display:none;">
<strong>Error:</strong> <span id="alertText"></span>
</div>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<h3 class="navbar-brand">Create Your Import File</h3>
</div>
</nav>
<div class="container">
<div class="m-4">
<table id="data" class="table">
<thead class="table-dark">
<tr>
<th>Sl. No</th>
<th>Account Number</th>
<th>Account Name</th>
<th>Account Description</th>
<th>Debit Amount</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- Default row for user input -->
<tr>
<td contenteditable="false">1</td>
<td contenteditable="true"></td>
<td contenteditable="true"></td>
<td contenteditable="true"></td>
<td contenteditable="true"></td>
</tr>
</tbody>
</table>
<button id="addRowBtn" class="btn btn-dark">Add New Row</button>
</div>
</div>
<div class="footer">
<input type="button" class="btn btn-dark" id="submitBtn" value="Submit" onclick="createCsvFile()">
<input type="button" class="btn btn-dark" id="cancelBtn" value="Cancel" onclick="cancelCsvPage()">
</div>
<div id="messageDiv"></div>
<!-- Add Bootstrap JS and Popper.js scripts here -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
let urldomain = 'DOMAIN';
let mainSuitelet = 'MAIN_SUITELET';
let csvSuitelet = 'CSV_SUITELET';
let mainSuiteletUrl = `https://${urldomain}${mainSuitelet}`;
let csvSuiteletUrl = `https://${urldomain}${csvSuitelet}`;
let rowCounter = 2;
document.addEventListener('DOMContentLoaded', function () {
// Add new row button click event
document.getElementById('addRowBtn').addEventListener('click', addNewRow);
});
/**
* Function to show an alert in the suitelet page
*/
function showAlert(message) {
let alertMessage = document.getElementById('alertMessage');
let alertText = document.getElementById('alertText');
alertText.innerText = message;
alertMessage.style.display = 'block';
setTimeout(function () {
alertMessage.style.display = 'none';
}, 8000); // Hide the alert after 3 seconds
}
/**
* Function to add new row on clicking the add new row button
*/
function addNewRow() {
let tableBody = document.getElementById('tableBody');
let currentRow = tableBody.rows[tableBody.rows.length - 1];
// Check if the current row is filled with data
if (isRowFilled(currentRow)) {
if (tableBody.rows.length < 2) { // Check the maximum limit
let newRow = tableBody.insertRow(tableBody.rows.length);
// Add cell for row number
let cellNumber = newRow.insertCell(0);
cellNumber.innerText = rowCounter++;
for (let i = 1; i < 5; i++) {
let cell = newRow.insertCell(i);
cell.contentEditable = true;
}
} else {
showAlert('Maximum limit reached (150 rows).');
}
} else {
showAlert('Please add values to the current row before adding a new one.');
}
}
/**
* Function to close the CSV creation page
*/
function isRowFilled(row) {
// Check if all cells in the row are filled with data
for (let i = 0; i < row.cells.length; i++) {
if (row.cells[i].innerText.trim() === '' || row.cells[i].innerText.trim() === 'Account') {
return false;
}
}
return true;
}
/**
* Function to validate if the entered value is in currency format
* @param {string} value
*/
function isValidCurrency(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
}
/**
* Function to cretae the CSV file
*/
function createCsvFile() {
let tableBody = document.getElementById('tableBody');
let csvContent = "Account Number,Account Name,Account Description,Debit Amountn";
for (let i = 0; i < tableBody.rows.length; i++) {
let row = tableBody.rows[i];
let accountNumber = row.cells[1].innerText;
let accountName = row.cells[2].innerText;
let accountDescription = row.cells[3].innerText;
let debitAmount = row.cells[4].innerText;
if (!accountNumber || !accountName || !accountDescription) {
showAlert('Please fill all the rows before creating a CSV file.');
return;
}
if (!isValidCurrency(debitAmount)) {
showAlert('Please enter valid debit amount.');
return;
}
// Construct CSV row
let csvRow = `${accountNumber},${accountName},${accountDescription},${debitAmount}n`;
csvContent += csvRow;
}
// Call the function to save the CSV to NetSuite File Cabinet
var fileId = saveCsvFileToNetSuite(csvContent);
}
/**
* Function to submit the created csv file to the NetSuite file cabinet
* @param {string} csvData
*/
function saveCsvFileToNetSuite(csvData) {
var xhr = new XMLHttpRequest();
var suiteletUrl = csvSuiteletUrl;
xhr.open('POST', suiteletUrl, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(encodeURIComponent(csvData));
console.log("xhr", xhr);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// Handle response from suitelet
const response = JSON.parse(xhr.responseText);
if (response.success === true) {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txtName");
var attachedFile = window.opener.document.getElementById("attachedFileName");
txtName.value = JSON.stringify(response.fileId);
if (response.fileId) {
window.opener.document.getElementById('createFile').disabled = true;
window.opener.document.getElementById('attachfile').disabled = true;
}
attachedFile.innerText = 'Attached File: ' + JSON.stringify(response.fileName);
}
window.close();
} else {
console.error(data.message);
let messageDiv = document.getElementById('messageDiv');
messageDiv.innerText = data.message;
messageDiv.style.color = 'red';
}
} else {
console.error('Error submitting CSV data. Status:', xhr.status);
}
}
};
}
/**
* Function to close the CSV creation page
*/
function cancelCsvPage() {
window.close();
}
</script>
</body>
</html>
Suitelet
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
/************************************************************************************************
* GRW_017_Import_Assistant_for_Acc_Plan
* This Suitelet script is used to create a CSV file and to store to the file cabinet
***********************************************************************************************/
define(['N/url', 'N/file', '../Libraries/grw_017_cm_import_assistant'],
/**
* @param{action} action
*/
(url, file, commonLib) => {
"use strict";
const LIBRARY = commonLib.library;
/**
* 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 {
if (scriptContext.request.method == "GET") {
let domain = url.resolveDomain({
hostType: url.HostType.APPLICATION,
});
let mainSuiteletUrl = url.resolveScript({
scriptId: LIBRARY.MAIN_SUITELET_SCRIPT_ID,
deploymentId: LIBRARY.MAIN_SUITELET_DEPLOYMENT_ID,
returnExternalUrl: false,
});
let csvSuiteletUrl = url.resolveScript({
scriptId: LIBRARY.CSV_SUITELET_SCRIPT_ID,
deploymentId: LIBRARY.CSV_SUITELET_DEPLOYMENT_ID,
returnExternalUrl: false,
});
let htmlFileObj = file.load({ id: LIBRARY.CSV_CREATION_PAGE });
let htmlContent = htmlFileObj.getContents();
htmlContent = htmlContent.replace("DOMAIN", domain);
htmlContent = htmlContent.replace("MAIN_SUITELET", mainSuiteletUrl);
htmlContent = htmlContent.replace("CSV_SUITELET", csvSuiteletUrl);
scriptContext.response.write({ output: htmlContent });
}
else {
let csvData = scriptContext.request.body;
log.debug("csv data", csvData);
let configRecData = LIBRARY.getConfigRecordDetails();
log.debug('configRecData', configRecData["CSV Files Through Form Folder Id"]);
let timeStamp = new Date().getTime();
let success = false;
let fileId = '';
let fileName = `Account_Plan-${timeStamp}.csv`;
let fileObj = file.create({
name: fileName,
fileType: file.Type.CSV,
contents: decodeURIComponent(csvData),
folder: configRecData["CSV Files Through Form Folder Id"],
});
fileId = fileObj.save();
if (fileId) {
success = true;
fileId = fileId;
fileName = fileName
}
let response = {
success: success,
fileId: fileId,
fileName: fileName,
message: success ? 'CSV file created successfully' : 'Failed to create CSV file. Please try again later.'
};
log.debug("Response passed", response);
//Send the response as JSON to HTML
scriptContext.response.write({
output: JSON.stringify(response),
contentType: 'application/json'
});
}
} catch (e) {
log.error('Error @ onRequest', e);
}
}
return { onRequest }
});