Copy/Original printing in Netsuite - oracle

I am trying to print original first time and copy after the first time printing. I have created a custom field that stored the timestamp of first time printing. So, the template will check first time the field is empty so "original" is printed and the timestamp will stored to the field. Then, when the template is printed after the first time it will check the field, find that there is a content (The timestamp) so it will print copy on the printed template. everything is work fine, buttt when trying to access the advance template of the applied transaction (like: Bill or any) it show an error like below the code!!! What is the issue?
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(['N/render','N/record'], function(render,record) {
function beforeLoad(context) {
var UserEventType = context.UserEventType;
var contextType = context.type;
var newRecord = context.newRecord;
var newRecordID= context.newRecord.id;
var currentDate = sysDate(); // returns the date
var currentTime = timestamp(); // returns the time stamp in HH:MM:SS
var currentDateAndTime = currentDate + ' ' + currentTime;
if (contextType == UserEventType.PRINT) {
var fieldId = 'custbody_first_print' // fieldId of your custom field / checkbox (or use a datetimestamp)
var isPrinted = newRecord.getValue({ fieldId: fieldId })
if (!isPrinted) {
var myRecord = record.load({id: newRecordID , type: newRecord.type}); // in the beforeLoad, editing the newRecord is not allowed, so you need to load the record first, edit and save.
myRecord.setValue({ fieldId: fieldId, value: currentDateAndTime })
myRecord.save();
}
}
}
function sysDate() {
var date = new Date();
var tdate = date.getDate();
var month = date.getMonth() + 1; // jan = 0
var year = date.getFullYear();
return currentDate = month + '/' + tdate + '/' + year;
}
function timestamp() {
var str = "";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridian = "";
if (hours > 12) {
meridian += "pm";
} else {
meridian += "am";
}
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
str += hours + ":" + minutes + ":" + seconds + " ";
return str + meridian;
}
return {
beforeLoad: beforeLoad,
};
});
The Error: Error during loading transaction for advanced printing Caused by: com.netsuite.suitescript.exception.NLServerSideScriptException: {"type":"error.SuiteScriptError","name":"SSS_MISSING_REQD_ARGUMENT","message":"load: Missing a required argument: id","stack":["createError(N/error)","beforeLoad(/SuiteScripts/Copy_Original.js:23)","createError(N/error)"],"cause":{"name":"SSS_MISSING_REQD_ARGUMENT","message":"load: Missing a required argument: id"},"id":"","notifyOff":false,"userFacing":true}

At first glance the base problem is that you are not passing a record ID to the record.load method.
A breakdown of the error:
What is the Error: "SSS_MISSING_REQD_ARGUMENT" (you are missing an argument that it needs in order to execute)
Where: "beforeLoad(/SuiteScripts/Copy_Original.js:23)" (the beforeLoad event in your suitescript Copy_Original, on line 23.)
What argument are you missing: "load: Missing a required argument: id" (after the : it tells you id)
I would change the names of your variables so they are different from the netsuite names. particularly newRecord, this will eliminate confusion and the possibility of you referencing a netsuite enum when you are trying to use your variable. (I believe that is what is happening here as I am able to get this to work on my record when using the following.)
function beforeLoad(context) {
var UserEventType = context.UserEventType;
var contextType = context.type;
var recObj= context.newRecord;
var recId= recObj.id;
var currentDate = sysDate(); // returns the date
var currentTime = timestamp(); // returns the time stamp in HH:MM:SS
var currentDateAndTime = currentDate + ' ' + currentTime;
if (contextType == UserEventType.PRINT) {
var fieldId = 'custbody_first_print' // fieldId of your custom field / checkbox (or use a datetimestamp)
var isPrinted = recObj.getValue({ fieldId: fieldId })
if (!isPrinted) {
var myRecord = record.load({id: recId, type: recObj.type}); // in the beforeLoad, editing the newRecord is not allowed, so you need to load the record first, edit and save.
myRecord.setValue({ fieldId: fieldId, value: currentDateAndTime })
myRecord.save();
}

It is worked now, check the sol. :
I should add && recId --->(context.newRecord.id)
if (contextType == UserEventType.PRINT && recId) {
var fieldId = 'custbody_first_print' // fieldId of your custom field / checkbox (or use a datetimestamp)
var isPrinted = recObj.getValue({ fieldId: fieldId })
if (!isPrinted) {
var myRecord = record.load({id: recId, type: recObj.type}); // in the beforeLoad, editing the newRecord is not allowed, so you need to load the record first, edit and save.
myRecord.setValue({ fieldId: fieldId, value: currentDateAndTime })
myRecord.save();

Related

How to deal with exception error when creating event from sheet?

In my mind, the script below takes a form submission gathered on a sheet and books it into a calendar (calId). In reality, however, the script falls apart at var event = thisCalendar.createEvent(:
Exception: Invalid argument: booker.
function calendarUpload() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 1");
var Avals = ss.getRange("A1:A").getValues();
var lastRow = Avals.filter(String).length;
Logger.log(lastRow);
for (var i = 2; i <= lastRow ; i++) {
var approvalStatus = sheet.getRange(i,1).getValue();
var name = sheet.getRange(i,8).getValue(); //Event name.
var description = sheet.getRange(i,9).getValue(); //Event description, agenda.
var date = sheet.getRange(i,5).getValue(); //Event date.
var formattedStart = Utilities.formatDate(new Date(date), 'Europe/London', 'MMMM dd, yyyy');
var startTime = sheet.getRange(i,6).getValue(); //Event starting time.
var formattedSTime = Utilities.formatDate(new Date(startTime), 'Europe/London','hh:mm');
var endTime = sheet.getRange(i,7).getValue(); //Estimated end time of event.
var formattedETime = Utilities.formatDate(new Date(endTime), 'Europe/London','hh:mm');
var guests = sheet.getRange(i,15,1,10).getValues(); //Event guests by email address.
var staffMember = sheet.getRange(i,10).getValue(); //Meeting with... Determines Calendar ID (CalID).
var calId = sheet.getRange(i,11).getValue(); //Calendar.
var booker = sheet.getRange (i,3).getValue(); //The person booking the meeting.
var bookerEmail = sheet.getRange(i,4).getValue(); //Email booker, adds to guest list.
var eventStatus = sheet.getRange(1,1,i,12).getCell(i,12);
//Create eventName based on reason for meeting.
if (name == "one-on-one"){
var title = "ℳ " + booker + " and " + staffMember;
} else {
var title = name
}
Logger.log(eventStatus);
Logger.log(title);
Logger.log(formattedStart);
Logger.log(formattedSTime);
Logger.log(formattedETime);
Logger.log(guests);
var startDateandTime = (formattedStart+" "+formattedSTime);
var endDateandTime = (formattedStart+" "+formattedETime);
Logger.log(startDateandTime);
if (approvalStatus == "Approved" && eventStatus.isBlank()){
var thisCalendar = CalendarApp.getCalendarById(calId);
Logger.log('calId: '+calId);
Logger.log(thisCalendar );
var event = thisCalendar.createEvent(
title,
new Date(startDateandTime),
new Date(endDateandTime),
{guests: guests && bookerEmail, description: description});
Logger.log('Event Series ID: ' + eventSeries.getId());
var setEventStatus = sheet.getRange(i,12).setValue('Event Series ID: ' + event.getId());
} else {
Logger.log("No Events Found");
}
}
}
The logs seem to show that things go smoothly. Is there anything that you'd do differently? What can I do about the Exception error?
Example sheet.

Set the sourceRange of Data Validation to an array of values

I'm creating a social media outreach tracker. I want to create a drop-down list of the contact name. The problem is that I have two sources of names on two different sheets.
I wrote a script that pulls the names from the two different sources and combines them to a single array.
I was hoping to set the source range as that array.
Here is my code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var auditionsSheet = SpreadsheetApp.getActiveSpreadsheet();
var castingDirectorsTab = auditionsSheet.getSheetByName("Casting Directors");
var contactsTab = auditionsSheet.getSheetByName("Contacts");
var socialMediaOutreachTab = auditionsSheet.getSheetByName("Social Media Outreach");
var lastRowCD = castingDirectorsTab.getLastRow();
var lastRowContacts = contactsTab.getLastRow();
var activeCell = socialMediaOutreachTab.getActiveCell();
var activeColumn = activeCell.getColumn();
// get data
var castingDirectorNameData = castingDirectorsTab.getRange(2, 1, lastRowCD, 1).getValues();
var contactNameData = contactsTab.getRange(2, 1, lastRowContacts, 1).getValues();
//get name data to a single arrays
var castingDirectorName = [];
castingDirectorNameData.forEach(function(yr) {
castingDirectorName.push(yr[0]);
});
var contactName = [];
contactNameData.forEach(function(yr) {
contactName.push(yr[0]);
});
// get rid of the empty bits in the arrays
for (var x = castingDirectorName.length-1; x > 0; x--) {
if ( castingDirectorName[x][0] === undefined ) {
castingDirectorName.splice( x, 1 )
}
}
for (var x = contactName.length-1; x > 0; x--) {
if ( contactName[x][0] === undefined ) {
contactName.splice( x, 1 )
}
}
//combine two data sources for data validation
var combinedNames = [];
combinedNames.push(castingDirectorName + contactName);
Logger.log (combinedNames);
Logger.log( typeof combinedNames);
// data validation set up and build
if (activeColumn == 1 && auditionsSheet.getName() == "Social Media Outreach") {
var range = auditionsSheet.getRange(activeCell.getRow(), activeColumn +1);
var sourceRange = combinedNames;
setDataValid_(range, sourceRange)
}
}
When I enter a date in Col A on Social Media Outreach, nothing happens in Col 2.
I was using an existing working nested data validation script I have but the sourceRange pulls from a sheet based on the value in the active cell. Here is that code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var aSheet = SpreadsheetApp.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
// data validation for Auditions Tab Projet Type to Project Details
if (aColumn == 9 && aSheet.getName() == 'Auditions') {
var range = aSheet.getRange(aCell.getRow(), aColumn + 1);
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('RefTables!' + aCell.getValue())
setDataValid_(range, sourceRange)
}
}
For this script when I select from the data validation drop-down, a new data validation comes up in the next col with the appropriate secondary data validation.
So the question is, can the source range be set to an array or do I need to put the names back into my sheet to reference a la the second script.
I've looked through the documentation and searched and can't find an answer. I'm relatively new to GAS and am not sure of all the inner workings of the data validation builder.

Nifi:Automatizied nifi

I have attribute names like startDate:2017-09-07 and endDate:2017-09-16 i want to reitrive data with this parameters and after writing response into the base i want to change this parameter i mean (startDate:2017-09-07 and endDate:2017-09-16 with 2017-09-17 and 2017-09-24) i tried this ecmascript code:
var OutputStreamCallback = Java.type("org.apache.nifi.processor.io.OutputStreamCallback");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
Date.prototype.isValid = function () {
return (Object.prototype.toString.call(this) === "[object Date]")
&& !isNaN(this.getTime());
};
function addDays(date, days) {
var result =new Date(date);
result.setDate(result.getDate() + days);
var dateFormated = result.toISOString().substr(0,10);
return formatDate(dateFormated);
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
var startDate = startDate.getValue(),
endDate = endDate.getValue(),
parametr=parameter.getValue(),
count=count.getValue();
var flowFile = session.crete();
var param=8;
var endDate = addDays(end, param*count);
var startDate = formatDate(newStart);
flowFile = session.putAttribute(flowFile, 'startDate', startDate);
flowFile = session.putAttribute(flowFile, 'endDate', endDate);
session.transfer(flowFile, REL_SUCCESS)
but i don't know how can i make my code known when it should increase count in order to change endDate and startTdate manually and replace it with valid startDate and EndDate
is there any service or processor i can use to simplify this task?

Icon calendar generator

Are there any calendar Photoshop/illustrator scripts which can automatically generate a date number similar to this calendar icon image?
I need similar icon with date (1,2,3..31) and name of every month but in .png format. I cannot use html/css3 and jquery to create icon.
Thank you for answers and help
Yes, it's possible. I like a challenge:)
First with the template image open
Second create a folder folder C:\temp\calendar (or change the destination path in the script)
Run the script below and it'll generate dates as defined with sdate & eDate (start & end date) - currently November, 30 to December 01
// Load in background image before running script
// call the source document
var srcDoc = app.activeDocument;
var sDate = new Date("November, 30, 2016 00:00:00");
var eDate = new Date("January, 01, 2017 00:00:00");
var myPath = "c:\\temp\\calendar"
printDate(sDate, eDate, myPath, srcDoc);
//-----------------------------
function printDate(start, end, apath, sauce)
{
if (start == undefined) return;
if (end == undefined) return;
// set long month names
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
str = "";
// main loop here
while(start <= end)
{
// Display the month, day, and year.
// getMonth() returns a 0-based number.
var monthNum = start.getMonth()+1;
var month = monthNames[monthNum-1].toUpperCase();
var day = start.getDate();
var year = start.getFullYear();
// alert(month + " " + day + " " + year);
// num padding
if (monthNum < 10) monthNum = "0" + monthNum;
if (day < 10) day = "0" + day;
var theDate = "cal_" + monthNum + "_" + day + "_" + year;
duplicateIt(theDate);
var day = start.getDate();
str = (day);
var newDate = start.setDate(start.getDate() + 1);
// fontface, size, R,G,B, text, X, Y
// print bigmonth
createText("Arial-BoldMT", 38.0,255, 255, 255, month, 582, 460);
// print big day
createText("Arial-BoldMT", 176.0, 0, 0, 0, day, 582, 1144);
var f = apath + "\\" + theDate + ".png";
// alert(f)
saveAsPNG(f, 10);
// close that saved png
app.activeDocument.close();
// get the original source doc
app.activeDocument = sauce;
// reset start
start = new Date(newDate);
}
}
// function DUPLICATE IT (str)
// --------------------------------------------------------
function duplicateIt(str)
{
// duplicate image into new document
if (arguments.length == 0) str = "temp";
var id428 = charIDToTypeID( "Dplc" );
var desc92 = new ActionDescriptor();
var id429 = charIDToTypeID( "null" );
var ref27 = new ActionReference();
var id430 = charIDToTypeID( "Dcmn" );
var id431 = charIDToTypeID( "Ordn" );
var id432 = charIDToTypeID( "Frst" );
ref27.putEnumerated( id430, id431, id432 );
desc92.putReference( id429, ref27 );
var id433 = charIDToTypeID( "Nm " );
desc92.putString( id433, str ); // name
executeAction( id428, desc92, DialogModes.NO );
}
// function SAVE JPEG(file name & path)
// --------------------------------------------------------
function saveAsPNG(afilePath)
{
// flatten it
activeDocument.flatten();
// save as a png
var pngFile = new File(afilePath);
pngSaveOptions = new PNGSaveOptions();
pngSaveOptions.embedColorProfile = true;
pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
pngSaveOptions.matte = MatteType.NONE; pngSaveOptions.quality = 1;
activeDocument.saveAs(pngFile, pngSaveOptions, false, Extension.LOWERCASE);
}
// function CREATE TEXT(typeface, size, R, G, B, content, Xpos, Ypos, justify)
// --------------------------------------------------------
function createText(fface, size, colR, colG, colB, content, X, Y)
{
// Add a new layer in the new document
var artLayerRef = app.activeDocument.artLayers.add()
// Specify that the layer is a text layer
artLayerRef.kind = LayerKind.TEXT;
artLayerRef.name = content;
//This section defines the color of the text
textColor = new SolidColor();
textColor.rgb.red = colR;
textColor.rgb.green = colG;
textColor.rgb.blue = colB;
//Get a reference to the text item so
// that we can add the text and format it a bit
textItemRef = artLayerRef.textItem
textItemRef.font = fface;
textItemRef.contents = content;
textItemRef.color = textColor;
textItemRef.size = size;
//pixels from the left, pixels from the top
textItemRef.position = new Array(X, Y)
just = Justification.CENTER;
activeDocument.activeLayer.textItem.justification = just;
}
It's save them as .PNG files named after the date.

Check cell value before post data to server

I'm having a problem checking cell value after an inline edit and before save data. Part of my ColModel is (without any unnesessary code):
{name:'event_start_date',index:'event_start_date',width:75,align:'center',editable:true,edittype:'text',editoptions:{size:'10',maxlength:'10',
dataInit:function(el){
$(el).mask('9999-99-99');
$(el).datepicker({dateFormat:'yy-mm-dd',
beforeShow: function(input, instance){instance.dpDiv.css({marginTop: '1px'});}})
}}
},
{name:'event_start_time',index:'event_start_time',width:70,align:'center',editable:true,edittype:'text',editoptions:{size:'8',maxlength:'8',
dataInit:function(el){$(el).mask('99:99:99');}}
},
{name:'event_end_date',index:'event_end_date',width:75,align:'center',editable:true,edittype:'text',editoptions:{size:'10',maxlength:'10',
dataInit:function(el){
$(el).mask('9999-99-99');
$(el).datepicker({dateFormat:'yy-mm-dd',
beforeShow: function(input, instance){instance.dpDiv.css({marginTop: '1 px'});}})
}}
},
{name:'event_end_time',index:'event_end_time',width:70,align:'center',editable:true,edittype:'text',editoptions:{size:'8',maxlength:'8',
dataInit:function(el){$(el).mask('99:99:99');}}
},
{name:'event_dur_calc',index:'event_dur_calc',width:90,align:'center',editable:false,edittype:'text',sorttype:'date',editoptions:{size:'10',maxlength:'10'}
}
I'm using double click to get inline edit mode. After user make some changes into date/time fields, new value calculated for cell "event_dur_calc":
$('#'+rowId+'_event_start_date').focusout(function(){recalc_dur(rowId);});
$('#'+rowId+'_event_start_time').focusout(function(){recalc_dur(rowId);});
$('#'+rowId+'_event_end_date').focusout(function(){recalc_dur(rowId);});
$('#'+rowId+'_event_endt_time').focusout(function(){recalc_dur(rowId);});
Functions fo calculating new time:
function mktime(){
var i = 0, d = new Date(), argv = arguments, argc = argv.length;
var dateManip = {
0: function(tt){ return d.setHours(tt); },
1: function(tt){ return d.setMinutes(tt); },
2: function(tt){ return d.setSeconds(tt); },
3: function(tt){ return d.setMonth(parseInt(tt)-1); },
4: function(tt){ return d.setDate(tt); },
5: function(tt){ return d.setYear(tt); }
};
for( i = 0; i < argc; i++ ){
if(argv[i] && isNaN(argv[i])){
return false;
} else if(argv[i]){
if(!dateManip[i](argv[i])){
return false;
}
}
}
return Math.floor(d.getTime()/1000);
};
function recalc_dur(rowId){
var event_start_date_txt = $('#'+rowId+'_event_start_date').val();
var event_start_time_txt = $('#'+rowId+'_event_start_time').val();
var event_end_date_txt = $('#'+rowId+'_event_end_date').val();
var event_end_time_txt = $('#'+rowId+'_event_end_time').val();
if (event_end_date_txt=='0000-00-00'){
$('#'+rowId+'_event_dur_calc').val('0000:00:00');
}else{
var start_d_pices = event_start_date_txt.split('-');
var start_t_pices = event_start_time_txt.split(':');
var end_d_pices = event_end_date_txt.split('-');
var end_t_pices = event_end_time_txt.split(':');
var start_time = mktime(start_t_pices[0], start_t_pices[1], start_t_pices[2], start_d_pices[1], start_d_pices[2], start_d_pices[0]);
var end_time = mktime(end_t_pices[0], end_t_pices[1], end_t_pices[2], end_d_pices[1], end_d_pices[2], end_d_pices[0]);
var delta = end_time-start_time;
var secs = delta % 60;
delta = (delta - secs) / 60;
if (secs.toString().length==1) var new_dur = ':0'+secs; else var new_dur = ':'+secs;
var mins = delta % 60;
delta = (delta - mins) / 60;
if (mins.toString().length==1) new_dur = ':0'+mins+new_dur; else new_dur = ':'+mins+new_dur;
var hours = delta;
if (hours.toString().length==1){new_dur = '000'+hours+new_dur;
}else if (hours.toString().length==2){new_dur = '00'+hours+new_dur;
}else if (hours.toString().length==3){new_dur = '0'+hours+new_dur;
}else new_dur = hours+new_dur;
$('tr[id=\"'+rowId+'\"] > td[aria-describedby=\"dfr_event_dur_calc\"]').html(new_dur);
}
}
If the new calculating time will be below zero (when start date/time is greater than end date/time), modal window with alert message is appers and data can't be saved and posted on server.
Is there any event in inline edit mode that fires before posting data, that I can use to check new calculating value to prevent incorrect data will be saved?
The current code of jqGrid on github contains beforeSaveRow callback function which will be called before saving. The changes was made after publishing of jqGrid 4.5.2, but the feature will be exist in the next version (>4.5.2) of jqGrid. So if you don't want use developer sources from github you can use the standard validation way: usage editrules with custom: true and custom_func which do the validation.

Resources