Listing folders in specified folder - netsuite

I'm trying this code to list the files inside cabinet's folder in NetSuite, but I can list only the files. I need to list the folders inside the folder with the ID: 28
The code I'm using:
var folder = 28;
var filters = new Array();
filters[0] = new nlobjSearchFilter('internalid', null, 'is', folder);
var columns = new Array();
var filename = new nlobjSearchColumn('name', 'file');
var fileid = new nlobjSearchColumn('internalid', 'file');
columns[0] = filename;
columns[1] = fileid;
var searchResult = nlapiSearchRecord('folder', null , filters , columns);
if(searchResult) {
for (var i = 0 ; i < searchResult.length; i++) {
alert(searchResult[i].getValue(filename)+searchResult[i].getValue(fileid));
};
};
The result:
warning File1.txt1938 11/22/2016 17:30:08.693
warning File2.txt1636 11/22/2016 17:30:08.693
warning File3.txt1939 11/22/2016 17:30:08.693
warning File4.txt4601 11/22/2016 17:30:08.693
this is correct, but it's listing only files, not folders?
Thanks!

Perform a UserEvent BeforeLoad function. All files have a parent folder ID.
// pass in the internal id of the file's parent folder
var folder = 415 // the folder ID we care about
var filters = new Array();
filters[0] = new nlobjSearchFilter('internalid', null, 'is', folder);
//file name and file internal ID
var columns = new Array();
var filename = new nlobjSearchColumn('name', 'file');
var fileid = new nlobjSearchColumn('internalid', 'file');
columns[0] = filename;
columns[1] = fileid;
// perform the search and loop through the findings
var searchResult = nlapiSearchRecord('folder', null , filters , columns);
if(searchResult) {
for (var i = 0 ; i < searchResult.length; i++) {
var f = searchResult[i];
//do what you want with f here
};
};
Credit: http://blog.prolecto.com/2014/01/09/get-netsuite-list-of-files-from-folder/

I was able to list the subfolders of folder with this code:
var folder = 3232;
var filters = new Array();
filters[0] = new nlobjSearchFilter('parent', null, 'is', folder);
var columns = new Array();
var filename = new nlobjSearchColumn('name');
var fileid = new nlobjSearchColumn('internalid');
columns[0] = filename;
columns[1] = fileid;
var searchResult = nlapiSearchRecord('folder', null , filters , columns);
if(searchResult) {
for (var i = 0 ; i < searchResult.length; i++) {
alert(searchResult[i].getValue(filename)+searchResult[i].getValue(fileid));
};
};

Related

Automatically unzipping files on google drive with google app script

I found and have made several codes to automatically unzip new files on my google drive with google app script, but none of them work. Can someone help me figure out how to get one code to work? The code is supposed to get a zip file from a given google drive folder and unzip it, so that the files within can be extracted and used in a different code.
Here are the six codes that might work, but don't. I only need one to work so I don't mind which one :)
Thank you in advance for your suggestions and help!
function unZip() {
var theFolderID = DriveApp.getFolderById(folderID);
var theFile = theFolderID.getFilesByType(MimeType.ZIP);
if (theFile.length > 0) {
for (var i in theFile) {
file = theFile[i];
var unZippedfile = Utilities.unzip(file);
var newfile = DriveApp.createFile(unZippedfile);
var fileId = SpreadsheetApp.create(newfile).getId();
var file = DriveApp.getFileById(fileId);
folderName.addFile(newfile);
root.removeFile(newfile);
}
}
}
function unZipItAll() {
var theFolder = getFolder_(folderName);
var theFile = theFolder.getFilesByType("application/zip");
if (theFile.length > 0) {
for (var i in theFile) {
file = theFile[i];
var unZippedfile = Utilities.unzip(file);
var newfile = DriveApp.createFile(unZippedfile);
var fileId = SpreadsheetApp.create(newfile).getId();
var file = DriveApp.getFileById(fileId);
folderName.addFile(newfile);
root.removeFile(newfile);
}
}
}
function unzip() {
var theFolderID = DriveApp.getFolderById(folderID);
var theFile = theFolderID.getFilesByType("application/zip");
while (theFile.hasNext()){
var fileBlob = theFile.next().getBlob();
fileBlob.setContentType("application/zip");
var unZippedfile = Utilities.unzip(fileBlob);
var newfile = DriveApp.createFile(unZippedfile);
var fileId = SpreadsheetApp.create(newfile).getId();
var file = DriveApp.getFileById(fileId);
folderName.addFile(file);
root.removeFile(newfile);
}
}
function unZipIt() {
var theFolder = DriveApp.getFolderById(folderID);
var theFile = theFolder.getFilesByType("application/zip");
var fileBlob = theFile.next().getBlob();
fileBlob.setContentType("application/zip");
var unZippedfile = Utilities.unzip(fileBlob);
var newDriveFile = DriveApp.createFile(unZippedfile[0]);
Logger.log(newDriveFile.getId())
}
function Unzip() {
var SourceFolder = DriveApp.getFolderById(folderID)
var DestinationFolder = DriveApp.getFolderById(folderID)
var ZIPFiles = SourceFolder.getFilesByType(MimeType.ZIP)
while (ZIPFiles.hasNext()){
var fileBlob = ZIPFiles.next().getBlob();
var unZippedfile = Utilities.unzip(fileBlob);
var newDriveFile = DestinationFolder.createFile(unZippedfile[0]);
}
}
function testzip(){
var theFolderID = DriveApp.getFolderById(folderID);
var theFile = theFolderID.getFilesByType("application/zip");
if (theFile.length > 0) {
for (var i in theFile) {
file = theFile[i];
var unZippedfile = Utilities.unzip(file);
var unzipstr = unZippedfile[0].getDataAsString();
var newfile = DriveApp.createFile(unzipstr);
folderName.addFile(newfile);
root.removeFile(newfile);
}
}
}

SheetJs converting string with date automatically to date angular

I am importing a CSV file in my angular application using sheetjs, Data is imported successfully. but it is converting string with a date to only date ignoring the string.
Code in ts file
readExcel() {
let readFile = new FileReader();
readFile.onload = (e) => {
this.storeData = readFile.result;
var data = new Uint8Array(this.storeData);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
this.worksheet = workbook.Sheets[first_sheet_name];
let processJsonData: Array<any> = XLSX.utils.sheet_to_json(this.worksheet, { raw: false });
console.log(processJsonData)
}
}
How to get both string and date in the json response. Please suggest

RCRD_DSNT_EXIST while creating user event script with aftersubmit function

I'm trying to write a user event script which loads the current record and populates a line item value through search after submit record. But, it is giving an error RCRD_DSNT_EXIST, even though the record exists.
function afterSubmit_SO(type){
try
{
//var record_type = nlapiGetRecordType();
var recordID = nlapiGetRecordId();
var context = nlapiGetContext();
var recordOBJ = nlapiLoadRecord('salesorder',recordID);
var source = context.getExecutionContext();
if(source == 'userinterface')
{
var line_count = recordOBJ.getLineItemCount('item');
nlapiLogExecution('DEBUG', 'line count ', line_count);
for(var i = 1; i <= line_count; i++)
{
var itemID = recordOBJ.getLineItemValue('item','item',i);
nlapiLogExecution('DEBUG', 'item ID', itemID);
var filter = new Array();
filter[0] = new nlobjSearchFilter('internalid', null, 'is', itemID);
var columns = new Array();
columns[0] = new nlobjSearchColumn('custitem_web_market_availability');
var a_search_results = nlapiSearchRecord('item',null,filter,columns);
if(a_search_results)
{
for(var x = 0; x < a_search_results.length; x++)
{
var item_web_availability = a_search_results[x].getText('custitem_web_market_availability');
nlapiLogExecution('DEBUG', 'value', item_web_availability);
}
} recordOBJ.setLineItemValue('item','custcol_web_item_availability',i,item_web_availability);
}
var submitID = nlapiSubmitRecord(recordOBJ, true, true);
}
}
catch(exception)
{
nlapiLogExecution('DEBUG','Exception Caught ','' + exception);
}
return true;
}```
It could be that your script is executing on the delete operation. I did not see any checking for this in the code you provided. If it is a delete operation then the after submit user event script wont be able to load the deleted record, this is why you get the error.
The type parameter of your afterSubmit function should contain the operation type. You can something like if (type == 'delete') { return true;} at the top of your script.

Angular get headers from excel uploaded using XLSX

I want to get the first row(name,email,mobile) as array from an uploaded excel file.
I am using XLSX.
I am getting whole data into array. But, I want only to read top line. because,
my excel file is quite large.
onFileChange(event) { //when user uploads xls file
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
const file: File = fileList[0];
const reader = new FileReader();
reader.onload = function (e) {
const arrayBuffer = this.result,
data = new Uint8Array(arrayBuffer),
arr = new Array();
for (let i = 0; i !== data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
const bstr = arr.join('');
const workbook: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
const firstSheetName: string = workbook.SheetNames[0];
const worksheet: XLSX.WorkSheet = workbook.Sheets[firstSheetName];
// getting all rows
console.log(XLSX.utils.sheet_to_json(worksheet, { header: 1 }));
// I want to get top row only.
console.log(XLSX.utils.decode_row('A1'));
};
reader.readAsArrayBuffer(file);
}
}
function get_header_row(sheet)
{
var headers = [];
var range = XLSX.utils.decode_range(sheet['!ref']);
var C, R = range.s.r;
* start in the first row */
/* walk every column in the range */
for(C = range.s.c; C <= range.e.c; ++C)
{
var cell = sheet[XLSX.utils.encode_cell({c:C, r:R})]
/* find the cell in the first row */
var hdr = "UNKNOWN " + C; // <-- replace with your desired default
if(cell && cell.t)
hdr = XLSX.utils.format_cell(cell);
headers.push(hdr);
}
return headers;
}
I've tried the file upload and below is my steps and result with both data and header,
This will also support multiple sheet within the excel sheet,
1.npm install --save xlsx
2.import * as XLSX from 'xlsx';
3.HTML Code:
<input type="file" (change)="onFileChange($event)">
4.Angular Typescript:
exceltoJson = {};
onFileChange(event: any) {
this.exceltoJson = {};
let headerJson = {};
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(event.target);
// if (target.files.length !== 1) {
// throw new Error('Cannot use multiple files');
// }
const reader: FileReader = new FileReader();
reader.readAsBinaryString(target.files[0]);
console.log("filename", target.files[0].name);
this.exceltoJson['filename'] = target.files[0].name;
reader.onload = (e: any) => {
/* create workbook */
const binarystr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });
for (var i = 0; i < wb.SheetNames.length; ++i) {
const wsname: string = wb.SheetNames[i];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws); // to get 2d array pass 2nd parameter as object {header: 1}
this.exceltoJson[`sheet${i + 1}`] = data;
const headers = this.get_header_row(ws);
headerJson[`header${i + 1}`] = headers;
// console.log("json",headers)
}
this.exceltoJson['headers'] = headerJson;
console.log(this.exceltoJson);
};
}
get_header_row(sheet) {
var headers = [];
var range = XLSX.utils.decode_range(sheet['!ref']);
var C, R = range.s.r; /* start in the first row */
/* walk every column in the range */
for (C = range.s.c; C <= range.e.c; ++C) {
var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
// console.log("cell",cell)
var hdr = "UNKNOWN " + C; // <-- replace with your desired default
if (cell && cell.t) {
hdr = XLSX.utils.format_cell(cell);
headers.push(hdr);
}
}
return headers;
}
5.Result
{filename: "uploadedexcel.xlsx", sheet1: Array(212), sheet2: Array(8), headers: {…}}
Results holds the uploaded excel name, data in the sheet1 and sheet2 and also header in the sheet1 and sheet2.
The uploaded excel sheets has sheet1 and sheet2.
I am using this code for single row header in excel sheet, but I want a two row header. Suggestions are welcome.
var Heading =[
[ "EMPLOYEE","SCORES","COMMENTS"]
];
const myworksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.emp ,{skipHeader:true});
XLSX.utils.sheet_add_json(myworksheet,this.emp,{skipHeader:true , origin: 'A2'});
XLSX.utils.sheet_add_aoa(myworksheet, Heading);
Here i am taking excel sheet from the blob
public DisplayExcelRows(ExcelURL from blob) {
var url = ExcelURL;
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
var excelrows: any;
oReq.onload = () => {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, { type: "binary" });
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
excelrows = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
//this will extract headers and other rows separately
this.data = excelrows;
this.header = this.data.shift(); //splitting headers and other rows
}
simplest way i found of doing this if you are using the json method then that is already generating objects with KEYS from the header so when using:
this.decoded = utils.sheet_to_json(workSheet);
just do this to get headers (assuming there was anything decoded):
this.columns = Object.keys(this.decoded[0]);
that will give you the columns, simply by getting the object keys which it used to generate them from the column names initially
// getting all rows
this.data = (XLSX.utils.sheet_to_json(worksheet, { header: 1 }));
// Fetch the first row
const header = this.data.shift();

Google Apps Script: Save Spreadsheet as ODS for Local Backup

I could use a hand. My company uses Google Sheets extensively, and we need a way to access files when we lose our Internet connection.
I could not get any of the examples found on this site to work for creating xls or ods from Google Sheets via script.
I did script a way to create csv backups, accessible from a local Google Drive folder. When used with an hourly trigger, this script creates csv files of every sheet of any spreadsheet modified in the last hour, puts them in a folder, and zips it inside a folder specifically for backups. From there I can move the zip to our local server.
function backUpMaker() {
var backupFolderId = '<Id of Backup Folder>';
var timeNow = new Date();
var newFolder = DocsList.createFolder(timeNow);
var newFolderId =newFolder.getId();
newFolder.addToFolder(DocsList.getFolderById(backupFolderId));
newFolder.removeFromFolder(DocsList.getRootFolder());
var sheets = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
while (sheets.hasNext()) {
var sheet = sheets.next();
var lastUpdate = sheet.getLastUpdated();
var timeHourAgo = new Date();
timeHourAgo = timeNow - 3600000;
if(lastUpdate >= timeHourAgo){
var sheetId = sheet.getId();
var csv = eachSheet(sheetId,newFolderId);
}
}
var backupFolder = DocsList.getFolderById(backupFolderId);
try{
backupFolder.createFile(Utilities.zip(newFolder.getFiles(), timeNow + '.zip'));
} catch(err) {
Logger.log(err);
}
newFolder.setTrashed(true);
}
function eachSheet(key,newFolderId) {
var ss = SpreadsheetApp.openById(key);
var ssId = ss.getId();
var ssName = ss.getName();
var howManySheets = ss.getNumSheets();
try{
for (var sheetIndex=0; sheetIndex < howManySheets; sheetIndex++) {
var activeSheet = ss.getSheets()[sheetIndex];
var activeName = activeSheet.getName();
if(activeName != 'Dropdowns'){ //Skip a hidden sheet used for validation on many of our spreadsheets
var activeId = activeSheet.getSheetId();
var time = new Date();
var fileName = time + " Backup: " + ssName + " " + activeName + ".csv";
var csv = contentCSV(ssId,activeId);
var folder = DocsList.getFolderById(newFolderId);
folder.createFile(fileName, csv, 'text/plain');
}
}
} catch(err) {
Logger.log(err)
}
}
function contentCSV(key,gid) {
var file = DocsList.getFileById(key);
var response = UrlFetchApp.fetch("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + key +
"&gid=" + gid + "&exportFormat=csv", oAuth());
var fileText = response.getContentText();
return fileText;
}
function oAuth() {
var oauthConfig = UrlFetchApp.addOAuthService("spreadsheets");
var scope = "https://spreadsheets.google.com/feeds"
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
var requestData = {
"oAuthServiceName": "spreadsheets",
"oAuthUseToken": "always",
};
return requestData;
}
How would I modify this to save as ods rather than csv? Or is there a better way to save backups? Thank you for your help!
Working code follows, thanks to input by #serge-insas :
Note: To make this work, enter your backup folder's id key, then choose ods or xlsx by commenting out the other choice. Then you need to set up a timed hourly trigger for backUpMaker(). Logs will catch errors for files that have been moved temporarily. Here goes:
function backUpMaker() {
var backupFolderId = '0B5--------------------1ZX1k';
//var exportFormat = 'ods';
var exportFormat = 'xlsx';
var timeNow = new Date();
var newFolder = DocsList.createFolder(timeNow);
var newFolderId =newFolder.getId();
newFolder.addToFolder(DocsList.getFolderById(backupFolderId));
newFolder.removeFromFolder(DocsList.getRootFolder());
var sheets = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
while (sheets.hasNext()) {
var sheet = sheets.next();
var lastUpdate = sheet.getLastUpdated();
var timeHourAgo = new Date();
timeHourAgo = timeNow - 3600000;
if(lastUpdate >= timeHourAgo){
try{
var key = sheet.getId();
var name = sheet.getName();
var fileName = timeNow + " Backup: " + name + "." + exportFormat;
var blob = contentBackup(key,exportFormat);
var folder = DocsList.getFolderById(newFolderId);
folder.createFile(blob).rename(fileName);
} catch(err){
Logger.log(err);
}
}
}
var backupFolder = DocsList.getFolderById(backupFolderId);
try{
backupFolder.createFile(Utilities.zip(newFolder.getFiles(), timeNow + '.zip'));
} catch(err) {
Logger.log(err);
}
newFolder.setTrashed(true);
}
function contentBackup(key,exportFormat) {
try{
if(exportFormat == 'xlsx'){
exportFormat = 'xls';
}
var file = DocsList.getFileById(key);
var response = UrlFetchApp.fetch("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + key +
"&exportFormat=" + exportFormat, oAuth());
var fileBlob = response.getBlob();
return fileBlob;
} catch(err) {
Logger.log(err)
}
}
function oAuth() {
var oauthConfig = UrlFetchApp.addOAuthService("spreadsheets");
var scope = "https://spreadsheets.google.com/feeds"
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
var requestData = {
"oAuthServiceName": "spreadsheets",
"oAuthUseToken": "always",
};
return requestData;
}
Your code needed very few changes to get ods files.
2 differences : the requested format in the urlFetch becomes "ods" and the returned object is not a string anymore but a blob.
Beside that, I kept all the sheet selection functions that you wrote and it seems to work fine as well. (nice job you did !).
Below is the full code I reproduced from yours and changed as described. My tests were working fine.
function backUpMaker() {
var backupFolderId = '0B3qS--------------TXdlY2M';
var timeNow = new Date();
var newFolder = DocsList.createFolder(timeNow);
var newFolderId =newFolder.getId();
newFolder.addToFolder(DocsList.getFolderById(backupFolderId));
newFolder.removeFromFolder(DocsList.getRootFolder());
var sheets = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
while (sheets.hasNext()) {
var sheet = sheets.next();
var lastUpdate = sheet.getLastUpdated();
var timeHourAgo = new Date();
timeHourAgo = timeNow - 3600000;
if(lastUpdate >= timeHourAgo){
var sheetId = sheet.getId();
var csv = eachSheet(sheetId,newFolderId);
}
}
var backupFolder = DocsList.getFolderById(backupFolderId);
try{
backupFolder.createFile(Utilities.zip(newFolder.getFiles(), timeNow + '.zip'));
} catch(err) {
Logger.log(err);
}
newFolder.setTrashed(true);
}
function eachSheet(key,newFolderId) {
var ss = SpreadsheetApp.openById(key);
var ssId = ss.getId();
var ssName = ss.getName();
var howManySheets = ss.getNumSheets();
try{
for (var sheetIndex=0; sheetIndex < howManySheets; sheetIndex++) {
var activeSheet = ss.getSheets()[sheetIndex];
var activeName = activeSheet.getName();
if(activeName != 'Dropdowns'){ //Skip a hidden sheet used for validation on many of our spreadsheets
var activeId = activeSheet.getSheetId();
var time = new Date();
var fileName = time + " Backup: " + ssName + " " + activeName + ".ods";
var blob = contentODS(ssId,activeId);
var folder = DocsList.getFolderById(newFolderId);
folder.createFile(blob).rename(fileName);
}
}
} catch(err) {
Logger.log(err)
}
}
function contentODS(key,gid) {
var file = DocsList.getFileById(key);
var response = UrlFetchApp.fetch("https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + key +
"&gid=" + gid + "&exportFormat=ods", oAuth());
var fileBlob = response.getBlob();
return fileBlob;
}
function oAuth() {
var oauthConfig = UrlFetchApp.addOAuthService("spreadsheets");
var scope = "https://spreadsheets.google.com/feeds"
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://accounts.google.com/OAuthAuthorizeToken");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
var requestData = {
"oAuthServiceName": "spreadsheets",
"oAuthUseToken": "always",
};
return requestData;
}

Resources