SuiteScript2.0 Please Add Value To Amount - javascript

I have a suitelet that is creating an order. Most times this works but sometimes, maybe 1 in 50 it fails with this error. "Please enter a value for amount."
The error is thrown when sommitting this.
if(orderLine.amount){
log.debug("itemrate", orderLine.itemrate);
salesOrder.setCurrentSublistValue({
sublistId : 'item',
fieldId : 'rate',
value : Number(orderLine.itemrate ? orderLine.itemrate : (orderLine.amount / orderLine.qty))
});
fieldServices.sleep(1000);
log.debug("Amount", orderLine.amount);
salesOrder.setCurrentSublistValue({
sublistId : 'item',
fieldId : 'amount',
value : Number(orderLine.amount)
});
}
The logs on a fail execution reads
2 View Debug Amount 26/05/2020 11:21 AM -System- 118.0909090909091
3 View Debug itemrate 26/05/2020 11:21 AM -System- 118.0909
So the amount is getting set with an amount but when I try to commit the line it doesn't work 100% of the time.

So here was the problem. I assumed the logging was on the line that I posted but it turned out it was trying to add another line with the amount of 0. JavaScript being JavaScript saw 0 as false in
if(orderLine.amount)
so the amount was never added to the line. I changed this if statement to read
if(orderLine.amount || orderLine.amount == 0)
This solved the problem.

Related

Map/reduce script not executed correctly (suitescript 2.0)

I am facing a weird problem where my code (specifically a record.save action) does not seem to be executed. The code is located in the 'reduce' phase of a suitescript 2.0 map/reduce script.
I have no clue what the cause for this might be. The logging does display 'is this executed' as stated in the example below but the lines below that do not seem to be executed. The logging does not show 'Order lines marked for order with ID:
//load the order
var SOrecord = record.load({
type: record.Type.SALES_ORDER,
id: orderId,
isDynamic: false
});
setLineValues(SOrecord, values, newShipmentId)
log.debug('Is this executed?');
//Save Order
var recId = SOrecord.save({enableSourcing: false, ignoreMandatoryFields: true});
log.debug('Order lines marked for order with ID: ', recId)
return recId;
Can anyone help?
UPDATE
//load the order
var SOrecord = record.load({
type: record.Type.SALES_ORDER,
id: orderId,
isDynamic: false
});
log.debug('Order Loaded! ', SOrecord);
//Loop lines present in values array
for(var i = 0; i < values.length; i++){
//Generate Shipment Line ID, 3 digits starting at 001
var tmpShipmentLineId = i + 1
var shipmentLineId = tmpShipmentLineId.toString().padStart(3, '0');
log.debug('Shipment Line ID: ', shipmentLineId)
//check if first fulfillment is done, if yes mark ready for second fulfillment
if(SOrecord.getSublistValue({sublistId: 'item', fieldId: 'custcol_il_send_ff_interface', line: values[i]}) == true){
log.debug('Line: ' + i, 'Mark ready for 2nd fulfillment')
//Set values
SOrecord.setSublistValue({
sublistId: 'item',
fieldId: 'custcol_send_to_ff_2nd',
line: Number(values[i]),
value: true
});
SOrecord.setSublistValue({
sublistId: 'item',
fieldId: 'custcol_shipment_id_2nd',
line: Number(values[i]),
value: newShipmentId
});
SOrecord.setSublistValue({
sublistId: 'item',
fieldId: 'custcol_shipment_line_id_2nd',
line: Number(values[i]),
value: shipmentLineId
});
}
//If not, mark ready for first fulfillment
else{
log.debug('Line: ' + i, 'Mark ready for first fulfillment')
//Set Values
SOrecord.setSublistValue({
sublistId: 'item',
fieldId: 'custcol_il_send_ff_interface',
line: Number(values[i]),
value: true
});
SOrecord.setSublistValue({
sublistId: 'item',
fieldId: 'custcol_shipment_id',
line: Number(values[i]),
value: shipmentId
});
SOrecord.setSublistValue({
sublistId: 'item',
fieldId: 'custcol_shipment_line_id',
line: Number(values[i]),
value: shipmentLineId
});
}
};
log.debug('SOrecord after changes: ', SOrecord);
SOrecord.save();
log.debug('Record Saved ', 'END');
Above you'll find an extended code snippet, for some reason all code outside of the for loop does not seem to be executed... Any ideas?
I'm not sure I understand the setup of the code here... the text refers to the first code snippet but the second one seems more informative. Here are some general things I would try but if you clarify what is printing and what is not on the second code snippet maybe I can help more...
(1) Add a try catch for better error handling. You seem to be getting a error that's not being logged.
(2) Try loading the record in dynamic mode and using selectLine -> setCurrentSublistValue -> commitLine
(3) it seems you are using "line: values:[i]" I don't have a example of what that returns but it seems it should be "line: i"
(4) have you logged this - SOrecord.getSublistValue({sublistId: 'item', fieldId: 'custcol_il_send_ff_interface', line: values[i]}) - if not please do and let us know what the value is...

How to set time between reports of users?

Is it possible to add a timer between reports of a user?I want to add 5 minutes between the reports of a user, or to make disable the button for reports for 5 minutes, even if the user refresh the page.It is possible?
Here is my button for report
<li class="share-link" style="float: right;left: 20px"><a data-toggle="modal" data-target="#exampleModal" href="javascript:void(0)" ><i class="rounded-x icon-flag"></i></a></li>
and after that I have a modal which send the report.
Here is the controller
public function careerReportCareerSolution(requ $request)
{
$reportExists = \App\Reports::where('user_id', $request['user_id'])
->whereDate('created_at', '>', Carbon::now()->subMinutes(5)->toDateTimeString())
->exists();
if($reportExists) {
// report has been created within 5 minutes
return Redirect::back()->withErrors(['error', 'Report created within the last 5 minutes']);
}
$report = \App\Reports::create([
'user_id' => $request['user_id'],
'username' => $request['username'],
'user_id_posted' => $request['user_id_posted'],
'username_posted' => $request['username_posted'],
'career_solution_id' =>$request['career_solution_id'],
'subject' =>$request['subject'],
'why_reporting' =>$request['why_reporting'],
'why_reporting_message' =>$request['why_reporting_message'],
'additional_message' =>$request['additional_message'],
'comment' =>$request['comment'],
'comment_user' =>$request['comment_user'],
'comment_id' =>$request['comment_id'],
]);
$id = $request['career_solution_id']; // looks like this is the ID you ar looking for
$career = CareerSolution::findOrfail($id);
$career->active = $request['active'];
$career->save();
if($report != ""){
flash('Career solution report submited', 'success');
}else{
flash('Career solution report', 'warning');
}
return Redirect::back();
}
}
So, I to set a time between reports, 3-5 minutes a user shouldn't be able to make a report.
Untested, however assuming you are using timestamps (created_at, updated_at) on the Report table, you should be able to achieve this with the following logic:
$reportExists = \App\Report::where('user_id', $request['user_id'])
->whereDate('created_at', '>', now()->subMinutes(5)->toDateTimeString())
->exists();
if ($reportExists) {
// report has been created within 5 minutes
return Redirect::back()->withErrors(['error', 'Report created within the last 5 minutes');
}
...
This will check whether or not a report has been created for that user within the last 5 minutes using the ->whereDate() eloquent query method.
The ->exists() method is used to find out if there is at least one occurance of the report.
A check is made to see if $reportExists is true. If so, the application will redirect the user to the same page with an error message (fill the ->withErrors() method with the appropriate message).
This should be placed before all other controller logic.

django-admin-bootstrapped messing with DateField, TimeField and PointField

I've just added django-admin-bootstrapped to my project. Almost everything is fine.
Actually there are two little bug whitch i'm wondering how to resolve.
The first one is about DateField and TimeField : There is no date/time picker when i'm under django-admin-bootstrapped. When i check the source code, there is no generated source code about the two picker. When i deactivate django-admin-bootstrapped, here is what is missing :
Next to the DateField :
<span class="datetimeshortcuts">
Today |
<a href="javascript:DateTimeShortcuts.openCalendar(0);"
id="calendarlink0"><img src="/static/admin/img/icon_calendar.gif" alt="Calendar">
</a></span>
Next to the TimeField :
<span class="datetimeshortcuts">
Now |
<a href="javascript:DateTimeShortcuts.openClock(1);"
id="clocklink1"><img src="/static/admin/img/icon_clock.gif" alt="Clock">
</a></span>
The second one is about a PointField (i'm working with postGis), without django-admin-bootstrapped, my field is fine, but when it's bootstrapped, i have an error onto OpenLayer.js :
OpenLayers.js:679 Uncaught TypeError: Cannot read property 'w' of null
So, two questions (using django 1.8 and django-admin-bootstrapped):
1- How to recover a date/time picker in the admin interface ?
2- How to recover my PointField map picker in the admin interface ?
Thank's all of you. (Here the same issue (1) on github : https://github.com/django-admin-bootstrapped/django-admin-bootstrapped/issues/168 but there is only external workarround (and i prefer a nativ one))
EDIT : From my sitepackage : ./django/contrib/gis/admin/options.py
I've directly changed the line who call OpenLayer.js to OpenLayer.debug.js to provide you more information.
In OpenLayer.debug.js line 40008 is the source of the error :
setMap: function(map) {
OpenLayers.Layer.prototype.setMap.apply(this, arguments);
if (!this.renderer) {
this.map.removeLayer(this);
} else {
this.renderer.map = this.map;
var newSize = this.map.getSize();
40008-> newSize.w = newSize.w * this.ratio;
newSize.h = newSize.h * this.ratio;
this.renderer.setSize(newSize);
}
},
Here the entire JS traceback on OpenLayer.debug.js + index of GeoDjango:
Uncaught TypeError: Cannot read property 'w' of null ==> OpenLayers.debug.js:40008
newSize.w = newSize.w * this.ratio;
OpenLayers.Layer.Vector.OpenLayers.Class.setMap ==> OpenLayers.debug.js:8349
layer.setMap(this);
OpenLayers.Map.OpenLayers.Class.addLayer ==> (index):614
geodjango_gps_point.map.addLayer(geodjango_gps_point.layers.vector);
geodjango_gps_point.init ==> (index):677 (anonymous function)
<script type="text/javascript">geodjango_gps_point.init();</script>
Two problems were describ and sorry for the poor lisibility. So here some answers :
1 - The DateField and Timefield seems to be issued and this will be fix :
Fix 168 (last update 3 days ago)
2 - My PointField show up correctly after adding this options to settings.py :
DAB_FIELD_RENDERER = 'django_admin_bootstrapped.renderers.BootstrapFieldRenderer'
Thank's all

Twitter like "x new tweets" with .arte or .ajax?

I've found this great example to implement a twitter like "x new tweets" http://blog.hycus.com/2011/03/14/realtime-updates-like-twitter-using-phpmysqljquery/
In this example the .arte jQuery plug-in is used. However I think it can be done just as the same with .ajax and I've coded as:
$.ajax({
url:'async.php? main='+$('.boxOfMainPage:first').attr('id'),
success:function(results)
{
if(results!='')
{
if(results.indexOf('boxOfMainPage')>=0)
$('#tweetEveryone').prepend(results);
else
$('#newTweet').html("<center><a href=''>I found "+results+" new tweets</a></center>").show();
}
}
});
This checks the results and loads the result to tweetEveryone. Async.php simply makes a mysql_query and brings the new results. I've actually done exactly the same with the example however when I click the 'new tweet's like it sometimes causes a postback. In the example I haven't experience it. Can it be because of the difference between .arte and .ajax ?
It's nothing about the differences between arte and ajax (in fact and in a short way, arte is ajax that is called with an interval, trying to do something like "long polling")
So, u have a link without href value, this must "reload" ur page, ie, it will perform a GET request to the actual URL in window.location. A postback performs a POST request, this is really happening?
--- edited ---
If you wanna to do the same effect from twitter, it's simple.. In async.php, instead u write an link element that shows how many tweets has after the old state, make this page write a JSON object with all tweets, then, ur ajax function must get this JSON and convert it into a JS object. With this object, u'll be able to count how many updates u have to show and exactly which are they.
So, ur function could be like this (assuming that "#boxOfMainPage" is ur tweets container):
$.ajax({
url : 'async.php?main='+$('.boxOfMainPage:first').attr('id'),
success : function (tweets) {
window.NEW_TWEETS = tweets;
if ( NEW_TWEETS && NEW_TWEETS.length ) {
$('#newTweet').html("<center><a href='#' onclick='showNewTweets()'>I found "+NEW_TWEETS.length+" new tweets</a></center>").show();
}
}
});
The showNewTweets functions will be:
function showNewTweets() {
if ( window.NEW_TWEETS && NEW_TWEETS.length ) {
$('#newTweet').hide().html("");
for ( tweet in NEW_TWEETS ) {
$("#boxOfMainPage").prepend(buildTweetHTML(tweet));
}
}
}
And buildTweetHTML:
function buildTweetHTML(tweet) {
var $tweetElm = $("<div class='tweet'>");
$tweetElm.append("<h2>"+tweet.user+" said:</h2>");
$tweetElm.append("<p>"+tweet.content+"</p>");
$tweetElm.append("<p class='time'>"+tweet.time+"</p>");
return $tweetElm;
}
Finally, async.php should write JSON object like this:
[
{ user : 'Rafael', content : 'The content from tweet', time : 'X time ago' },
{ user : 'George', content : 'The content from tweet', time : 'Y time ago' }
{ user : 'Jack', content : 'The content from tweet', time : 'H time ago' }
]

Javascript Error,Escaping Problem,Grid not working,Error on Firebug

we are just started with Sigma Grid ,and it is awesome in its functionality when we compared to other Grids.
But i encountered some problem with Sigma Grid ,or may be with javascript.
I dont know whether the problem is with Grid or with my code.
I have a table with 3 fields namely MailID,MailName,MailData.
MailID is int ,MailName and MailData contains HTML content and it save as string in database.
When i load the Grid,i have some problems.
Problem 1 :
As i said above the Maildata contain html content,the following image is just a example with <*b> ,u can see that the HTML is automatically rendering on the grid itself ,i need the exact string.
please check the following image.
Problem 2 :
as u can see i have links on the grid,for edit,send,delete but on one filed its damaged.[check the image below ]
the code i used to render links is following .
{id: 'mailid' , header: "Action", width :120 , resizable : false, sortable : false , printable : false ,
renderer : function(value ,record,columnObj,grid,colNo,rowNo){
var no= record[columnObj.fieldIndex];
var cod = (record['maildata']);
return 'Edit | Delete';
Problem 3 :
The third value of MailData is 5 and it is integer ,when i alert the value its shows it correctly.
check the following image.
But when i alert the second value of maildata it giving error ,the second value of MailData is "hai newuser" ,it showing the following error on firebug.
missing ) after argument list
alert(hai newuser)
check the image below.
But when i alert 9th value of MailData it run correctly ,the content is <b>poy</b> ,this one is also save as string,but the grid automatically BOLD [which i dnt like].Check the image below.
also there are some others the 7the value contain ;".: etc ,also /b ,when i alert the data it showing the following error,
unexpected end of XML source
alert(<b>jjfdslkdjflsdnfsldfnf
dsOptions and ColOptions are following .
var dsOption= {
fields :[
{name : 'mailid' },
{name : 'mailname',type:"text" },
{name : 'maildata',type:"text" }
],
recordType : 'object',
}
function my_renderer(value ,record,columnObj,grid,colNo,rowNo)
{
var no= record[columnObj.fieldIndex];
return "<img src=\"./images/flag_" + no.toLowerCase() + ".gif\">";
}
function showalert(no)
{
$(document).ready(function()
{
$.post("http://localhost/power/index.php/power/give",{ name: no}, function(data)
{
//alert("Data Loaded: " + data);
$("#editor").show("fast");
$( '#txtar' ).ckeditor();
$('#txtar' ).val( data.maildata );
//$("#editor").html(data);
},"json"
);
});
}
var colsOption = [
{id: 'mailid' , header: "Mail ID" , width :60},
{id: 'mailname' , header: "Mail Name" , width :160 ,type:"text"},
{id: 'maildata' , header: "Mail Data" , width :190,type:"text" },
{header: "Group" , width :70,
editor : { type :"select" ,options : {'php':'php','asp':'asp'}
,defaultText : 'php' } },
{id: 'mailid' , header: "Action", width :120 , resizable : false, sortable : false , printable : false ,
renderer : function(value ,record,columnObj,grid,colNo,rowNo){
var no= record[columnObj.fieldIndex];
var cod = (record['maildata']);
return 'Edit | Delete';
} }
];
I am littlebit new in Javascript and Sigmagrid,i think that i am doing something worst with codes,pls help me to success.
Thank you.
Note : i posted the same Question on Sigma Grid Forum too,i think that it is not a problem.
Problem 2
The string cod contains a >
Problem 3
The string hai newuser needs to be contained in " or ' or it is considered a variable name
Basically you have to decide -- are you going to validate the html or not. If you don't validate the HTML then html errors in the data will show as errors on your page. You could also HTML escape the html so you will see the HTML codes -- this is probably the best plan.
Other sites use (like this one) use markdown -- this is easier to validate -- then they generate the actual HTML before display.
In addition you are having problems with the alert. Alert displays strings not HTML so you will see what you are seeing -- different results than expected depending on the HTML.
I would take a step back and ask yourself -- what is the type of the data, how am I going to display it. How am I going to validate that if it is HTML it is valid.
There are the problems you need to address -- your examples all stem from this problem.

Categories

Resources