custom calculation with results being in Currency format - javascript

I am making a PDF with a custom calculation script and I want to get the product of 2 fields with the results in the format of currency and for the life of me I cant figure it out. I am relatively new to a lot of this.
Here is the code I currently have:
var QtyRow1 = (this.getField( "QtyRow1").value); // the value of QtyRow1;
var CostRow1 = (this.getField( "CostRow1").value); // the value of CostRow1;
var t1 = QtyRow1 * CostRow1; // the value all TotalRows;
if ( t1 < .01 ) {
// t1 will remain blank if total of CostRow1 * QtyRow are less than 1;
event.value = "";
} else {
// otherwise will calculate total of all TotalRows;
event.value = t1;
}
Additionally here is a link to my PDF I am working on from my google drive. I am trying to take the Quantity and Cost of each row and so a total in the format of Currency from the product of the quantity and cost.

So my problem was I wasn't identifying t1 as a number format with in the JavaScript code so when I would go to the format tab under the form field properties and select that I wanted it to formatted to number and currency it wouldn't work cause it would give me an error saying the "t1" hasn't been properly formatted. So all I did was within the if statement made sure to tell JavaScript that t1 needed to be formatted to a number and did so by doing this: event.value = (Number(t1)) as to where before I just had event.value = t1. That fixed it and now everything works great.
Here is a link to the new PDF with the new code in it:
Click Here
// the value of form field QtyRow1;
var QtyRow1 = (this.getField("QtyRow1").value);
// the value of form field CostRow1;
var CostRow1 = (this.getField("CostRow1").value);
// the product of form fields QtyRow1 and CostRow1;
var t1 = QtyRow1 * CostRow1;
// if statement for results
if( t1 < .01 )
{
// t1 will remain blank if total of form fields CostRow1 * QtyRow are less than .01;
event.value = "";
} else {
// otherwise will caclculate the product of form fields QtyRow1 and CostRow1;
event.value = (Number(t1));
}

Related

Using JS to sum a column of values from an external text file containing donation histories of a db of donors

I need some assistance figuring out how to sum a column of dynamic totals that could be a positive or negative dollar amount, or an indication of stock shares.
I have a tab-delimited text file of donor contributions for that I am matching up against a CSV file of other related customer data that I am using to create a statement letter which will show a "donation history" of a particular donor. Each donor has a different amount of donations, and to complicate things, the column of data for a particular donation record could show either "$1,000.00" or "($1,000.00)" or "2 Shares APPL". The number with the parentheticals is of course, representing a negative number.
At the end of this column, I need to show a string that will read either "Total: $1,000.00," or if any of the donation history contains a donation record that included shares of stock the returned string will simply read, "$1,000.00 & Stock."
I have been racking my brain trying to come up with the JS rule that can achieve this. I have the JS rule that is generating the donation history correctly, but summing the donation amount column is causing me to go crazy...
Here is the JS for generating my donation history list in the letter (this seems to be working fine):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
var lb = "<br>\n";
var matches = new Array();
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var dateVariable = contributionList.GetFieldValue(i, "Donation Date");
var ministryVariable = contributionList.GetFieldValue(i, "Ministry Designation");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
if (donor_id == idVariable)
matches.push(tsSettings + dateVariable + ts + giftVariable + ts + ministryVariable);
}
//return matches;
return matches.join(lb);
Now here is the JS code that is not working just fine. I am trying to tally the donation amount column, it only returns "Total: $0.00 & Stock" every time (I have tried to explain my thought process via comments):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var sum = 0;
var shares = 0;
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
var totalStr = "Total ";
var stockStr = " & Stock";
var totalFormatted = FormatNumber("$#,###.00", Math.max(0, StringToNumber(sum)));
// Match data from linked file to current Supporter
if (donor_id == idVariable) {
// Look at current record and see if it contains the word "Share(s)"
// or not and act accordingly
if (giftVariable.match(/(^|\W)share($|\W)/i) || giftVariable.match(/(^|\W)shares($|\W)/i)) {
// Turn switch "on" if donation amount is a share or shares so
// we can have the " & Stock" appended to our string.
shares = 1;
// Because this donation is/are shares, we must "zero" this
// amount to make the math work when we sum everything up...
giftVariable = 0;
// This is where we are keeping our running total...
sum += giftVariable[i];
} else {
// This record was not a donation of share(s) so we now have to
// determine whether we are dealing with postive or negative numbers
// and then strip out all of the non-number characters, remove and
// replace the () whis just a "-," leaving us with a number we can
// work with...
// If number has parenthesis, then deal with it...
if (giftVariable.indexOf("(")) {
// Strip out all the ()$, characters...
giftVariable = giftVariable.replace(/[()$,]/g,"")
// Append the minus sign to the number...
giftVariable = "-" + giftVariable;
sum += giftVariable[i];
} else {
giftVariable = giftVariable.replace(/[$,]/g,"");
sum += giftVariable[i];
}
}
}
}
// Return Total...
if (shares == 1) {
return tsSettings + totalStr + ts + totalFormatted + stockStr;
} else {
return tsSettings + totalStr + ts + totalFormatted;
}
Any assistance would be greatly appreciated!
The problem (and code) needs to be broken into smaller, atomic steps. From your description it sounds like you should:
load a text file into memory
for each line in the file
extract: {
donor_id
charity
gift
and store the results in a contributions dictionary
for each item in the contributions dictionary
transform gift string into {
dollarAmount: float with a default of 0.0
stock: name with a default of ""
}
create an empty dictionary called totals
each item will have the shape {
id
dollarAmount as a float
stocks an an array
}
for each item in the contributions dictionary
lookup the id in the totals dictionary
if it exists
totals[id].dolarAmount += item.dollarAmount
totals[id].stocks.push(item.stock)
otherwise
totals[id].dollarAmount = item.dollarAmount
totals[id].stocks = [item.stock]
normalize your charities
for each item in totals dictionary
remove any empty strings from item.charities
create your report
for each item in totals dictionary
write`${item.id} donated `${item.dollarAmont}` ${item.stocks.length > 1 ? 'and stock' : ''
I believe you are trying to do too many things at once. Instead, the goal should be to normalize your data before you attempt to perform any calculations or aggrgrations, then normalize your aggregrations before writing your summaries or reports.
I would also stay away from using any direct string manipulation. You should have a dedicated function whose only purpose is to take a string like "($20.34) and 1 share of APPL" and return either 20.34, -20.34, or 0.0. And a different function whose only purpose is to take the same string and return either true or false is stock was present.

Google Sheets Calendar

I would like some help in pulling certain data from a google form linked to a spreadsheet and set a certain value in the date of a certain employee. For example if he/she marked as Vacation Leave then the letter V will be marked under the Date. I have attached the link to my calendar to give an example, I have tried searching the net and this is my second time posting here.
I started the Code but I am stuck in actually finding the Cell for a certain date and inserting the letter.
https://docs.google.com/spreadsheets/d/1uFTR2_B7T0QBr7fTflByFffmmiszbNj_RaCvLEfYRCA/edit?usp=sharing
function setData(){
//Spreadsheets
var ss = SpreadsheetApp;
var data = ss.getActiveSpreadsheet().getSheetByName("Data");
var calendar = ss.getActiveSpreadsheet().getSheetByName("Calendar");
//Get last row / Individual Cells from Form
var lRow = data.getLastRow();
var lRowData = data.getRange(lRow,1,1,17).getValues();
var approval = data.getRange(lRow,17,1,1).getValue();
var leave = data.getRange(lRow,9,1,1).getValue();
var agentName = data.getRange(lRow, 5,1,1).getValue();
var dateBefore = data.getRange(lRow, 10,1,1).getValue();
var dateAfter = data.getRange(lRow, 11,1,1).getValue();
//Calander Variable Arrays
var allDates = calendar.getRange("LA1:NJ1").getValues();
var allNames = calendar.getRange("A4:A160").getValues();
for(var i = 0; i<allNames.length; i++){
if (approval === "Approved" && allNames[i][0] === agentName){
//Here I need it to insert the dates under the correct name and date with a value of V H S M U T.
};
};
};
You are building a spreadsheet-based Leave Calendar based on information from a form response. Based on your existing Calendar, you are having problems identifying the relevant leave dates, and then filling calendar cells to indicate proposed leave.
The problem is there are no fields in rows 1,2 or 3 of Calendar that have the same date format as the Start Date and End Date fields on Form. As a result, there's no easy way to search for a match of the form data fields.
The solution, in my view, is to change the format of the date fields in rows 2 and 3 and enable a search to be match.
Row 2
the existing format is "d" - day of the month (Numeric)
change the format to match the Form Start/End dates: "d-MMM-yyyy".
the font colour for this field can be used to "hide" these dates, and the column width reduced also.
Row 3
the existing format is "E" - day of the week (Name)
change the format to combine the existing formats of rows #2 and #3 - "E-d"
Aspects of the script
the form data is retrieved as getDisplayValues(). The purpose of this is to get the date as a string to facilitate the search.
Two sets of Calendar data are obtained
1) the dates row (Row#2)
2) the names column (Col #1). The Javascript map method is used to convert names from a 2D array to a 1D array. This creates an array that can be easily searched.
the Javascript indexOf method is used to find the Column match for the start and end dates, and to match the name in the Calendar Column (which yields the Row)
the script loops through the number of days leave to create a temporary array of "V" values.
using the row number and the start and end column numbers, a range can be defined on calendar and then updated from the values in the temporary array.
Presumably your function would be triggered by onFormSubmit(e).
Form data
Calendar - Before
Calendar - After
function so5871726503(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var form = ss.getSheetByName("Form");
var calendar = ss.getSheetByName("Calander");
//get form data
var formdataRange = form.getRange(6,1,1,9);// test data
var formData = formdataRange.getDisplayValues(); // display values to format date as string
//get the employee name, start date and end date
var formName = formData[0][1];
var formSD = formData[0][3];
var formED = formData[0][4];
// Logger.log("DEBUG: name = "+formName+", start date = "+formSD+", end date = "+formED);
//get Calendar variables
var calLR = calendar.getLastRow();
var calLC = calendar.getLastColumn();
var caldateStart = 9;
var calnameStart=4;
// get Calendar dates
var calDateRange = calendar.getRange(2,caldateStart,1,calLC-caldateStart+1);
var calDateValues = calDateRange.getDisplayValues();
// get Calendar names
var calNameRange = calendar.getRange(calnameStart,1,calLR-calnameStart+1);
var calNameValues = calNameRange.getValues();
var calNames = calNameValues.map(function(e){return e[0];});//[[e],[e],[e]]=>[e,e,e]
// there should be some error checking on indexof results = -1 in case there is a mismatch.
// find form start date in calender
var startdateresult = calDateValues[0].indexOf(formSD);
var startdateresultcol = startdateresult+caldateStart;
// Logger.log("DEBUG: start date result = "+startdateresult+", column = "+startdateresultcol);
// find form end date in calender
var enddateresult = calDateValues[0].indexOf(formED);
var enddateresultcol = enddateresult+caldateStart;
// Logger.log("DEBUG: end date result = "+enddateresult+", column = "+enddateresultcol);
// find form name in calender
var nameresult = calNames.indexOf(formName);
var nameresultrow = nameresult+calnameStart;
// Logger.log("DEBUG: name result = "+nameresult+", row = "+nameresultrow)
// calculate number of days leave
var daysleave = enddateresultcol-startdateresultcol+1
// Logger.log("DEBUG: days leave = "+daysleave)
// create array variable to hold leave data
var leave=[];
// loop to create data to fill Calendar
for (i=0;i<daysleave;i++){
leave.push("V");
}
// Logger.log(leave); // DEBUG
// build leave range
var calLeave = calendar.getRange(nameresultrow,startdateresultcol,1,daysleave);
//Logger.log(calLeave.getA1Notation()); //DEBUG
// Update the leave range
calLeave.setValues([leave]);
}

PDF Toggle different values in auto populated fields while not affecting original input

I am working on a pdf file with many pages with a persons' name on eacb page. I named the label the same thing in all the fields to easily automate the name throughout the pdf.
The client wants functionality to change the name throughout the document, so now when I try to change the name on a page besides the first (When it asks your name initially) it changes all fields, for example:
I was thinking of running simple javascript in each field:
this.getField("Date") = event.value || event.value = event.value;
I got to thinking of the scope of the script. I am working in the actions tab in the property so do I really need to set variables? So I did:
var name000 = this.getField("Name");
name000 == event.value || event.value == event.value;
Then I went through the entire document and uniquely changed all the field names. Instead of Date for all, Name00, Name01, Name02, Name03, etc, all the way to Name24.
Used for the first few labels:
this.getField("Date").value = this.getField("Date00").value;
this.getField("Date").value = this.getField("Date01").value;
this.getField("Date").value = this.getField("Date02").value;
The problem with this scenario is after Date00 the fields are empty like I haven't done anything. Added variable as so, same situation
this.getField("Name") = event;
// set value of field "Name" to this field's value;
this.getField("Name00").value = event.value;
// end on blur action for field Date;
var Name1 = this.getField("Name");
var Name2 = this.getField("Name01");
Name2.value = Name1.value;
// end on blur action for field Date;
var Name1 = this.getField("Name");
var Name3 = this.getField("Name02");
Name3.value = Name1.value;
Third label is blank, so I assigned unique variables named the Name Field differently and still blank after I assign more than one field.
var name000 = this.getField("Date");
name000 == event.value || event.value == event.value; <-- This has the same problem.
9/2 update.
this.getField("Name") = event.value || event.value = event.value; Onblur Javascript errors "SyntaxError: Invalid assignment on left-hand side." Just from this error alone I don't want to go through the entire form to correct all Field names "Name". I have them named differently:
Name, Name01, Name02, 03,10, until Name24
Plus it seems time consuming togo to every field copying:
this.getField("Name") = event.value || event.value = event.value;
this.getField("Name00") = event.value || event.value = event.value;
this.getField("Name01") = event.value || event.value = event.value;
this.getField("Name02") = event.value || event.value = event.value;
this.getField("Name03") = event.value || event.value = event.value;
" \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"
this.getField("Name24") = event.value || event.value = event.value;
it doesn't compute anyways.
Tries an OOP script for more automation and less code:
var i f fi nv;
function n(f){
return n > 9 ? "" + n: "0" + n;
}
f = this.getField(“Name") = event.value;
fi = this.getField("'Name' + i") = event.value;
nv = event.value = event.value;
while (i = 0; i < i++) {
return i <= 24;
};
f fi || nv;
I get an error though, missing ';' at line 2?
From the blog I noticed they used one script for only the first field to complete the task. Can I change the update all same fields through the PDF main Javascript meta data? Has anyone done this?
Is there a simple way or anyway to solve this? I have spent way too much time on this.
Further investigation I discovered that each field needs to be unique, every field except the primary needs JavaScript to run OnBlur in the actions tab in the fields' property:
//Set the source and destination vars:
var source = this.getField("ClientName");
var destination = this.getField("CN2");
//See if destination is empty and if so, insert source value
if(destination.value==''||destination.value==null){destination.value=source.value}

jquery calculations as per selected dropdown value loop

Iam trying to do a calculation. When a user selects a dropdown currency. The system calculates and converts the selected currency from the dropdown to INR currency values. The records are coming from mysql db and the record count will be from one record to 300 records. Here the user needs to change each currency from the drop down and the system converts this selected currency value to INR value. Its really a hectic task. So If the user changes one currency value from dropdown, the system should change the entire row currency value to the selected dropdown value and the system should calculate on certain formulae to change the value to INR. All these is working fine.
Now the issue iam facing is to implement the formulae to the jquery.
Here is the fiddle what i have done:
Fiddle
If you can check the fiddle in the jquery part i have used a formula
var newTotal = currency==="INR" ? totalINR : (totalINR * conversionRate / row.find('.inrvalue').val()).toFixed(3);
This above formula wrong:
The actual formula iam looking at is
if (currency==="INR")
{
var newTotal = totalINR;
} else if (currency==="USD")
{
var newTotal = (row.find('.total1.').val() * row.find('.inrvalue').val());
} else {
var newTotal = ((row.find('.inrvalue').val() / conversionRate) * row.find('.total1.').val());
}
How will i change the existing formulae to this? When i implement this formula, iam getting an error Uncaught Error: Syntax error, unrecognized expression: .. Help Appreciated
your function is almost right, you have only one "extra" dot after "total1"
you can safely change
var newTotal = currency==="INR" ? totalINR : (totalINR * conversionRate / row.find('.inrvalue').val()).toFixed(3);
for
var newTotal = 0;
if (currency==="INR")
{
newTotal = totalINR;
} else if (currency==="USD")
{
newTotal = (row.find('.total1').val() * row.find('.inrvalue').val());
} else {
newTotal = ((row.find('.inrvalue').val() / conversionRate) * row.find('.total1').val());
}
hope this helps

Calculate total after retriveing tax rate from JSON

I have 1 select, 2 text inputs & some JSON data in a form:
select input: List of Suppliers
text input 1: Net Amount
text input 2: Gross Amount
JSON Data:contains the rates of various suppliers as JSON in supplier_tax_rates
I am calculating Gross Amount something like this(pseudo code):
grossAmount = NetAmount + ((currently_selected_supplier.tax_percentage_charged / 100) * netAmount)
Here is the complete code:
Calculate total after retriveing tax rate from JSON
Now, this should work but it doesn't. I get NaN(not a number), means something is wrong. But I have trouble find where.
JSfiddle
You have multiple problems in your code. Here is the correct version:
var taxRates = $.parseJSON(supplier_tax_rates);
var getTaxRate = function(id) {
for (var i in taxRates) { // correct loop definition
if (taxRates[i].id == id) { // check you get id correctly
return taxRates[i].tax_percentage_charged; // instead of 'rate'
}
}
};
$('#PurchaseNetAmount').on('change', function(event) {
var taxRatesId = $('#PurchaseSupplierId').val();
var netAmount = parseFloat(this.value);
var grossAmount = netAmount + ((getTaxRate(taxRatesId) / 100) * netAmount);
$('#PurchaseGrossAmount').val(grossAmount);
});
DEMO: http://jsfiddle.net/A9vmg/18/
Your problem is in the look up function.
for(TaxRate in supplier_tax_rates ){
supplier_tax_rates is a string, not a JSON object
Than after you fix that you will have another error
return rate;
What is rate?
Learn to use console.log() or breakpoints so you can step throught your code and debug it.
getTaxRate(taxRatesId) return undefined

Categories