Updating final sheet without losing data - javascript

I have several sheets in the same spreadsheet, sheets with data to facilitate my job when i do my script that generates sheets that i need, and my problem is when i add more data, is there any solution to update the final sheet without losing what I wrote before .
My exemple : Every user I add the sheet of data, if I execute the function it'll add a timesheet with its name in final sheet, and I don't know how to keep the data i added in the timesheets of users because, as you know, the execution of the function will crush it and generate a new timesheet for all the users
Here is the code of the function that generates the timesheets:
function generateTimeSheet(){
Logger.clear();
var semaine=1;
var projectSheet = ss.getSheetByName("Liste Projets");
var usersSheet = ss.getSheetByName("Utilisateurs");
var tabProjectsLibs = getProjectList();
//Récupération de la liste des utilisateurs
var tabUsers = getUsersList();
//Suppression des colonnes vides
for(i = 1; i < 13; i++){
//Nombre de jours du mois
var date = new Date(i + "/01/" + year);
var nbDays = getNbJours(date);
//Nettoyage de la feuille
var currentMonthSheet = getSheetByMonth(tabMonth[i - 1]);
var rows = currentMonthSheet.getMaxRows();
var cols = currentMonthSheet.getMaxColumns();
var currentMonthRange = currentMonthSheet.getRange(rows, cols);
currentMonthSheet.clear();
currentMonthSheet.clearFormats();
//Suppression des lignes et colonnes inutiles
try{
currentMonthSheet.deleteColumns(2, cols - nbDays );
}catch(e){
//Logger.log("erreur : " + e);
}
try{
currentMonthSheet.deleteRows(2, rows - 3);
}catch(e){
//Logger.log("erreur : " + e);
}
var numProjects = getProjectNumber();
var prjLines = 2;
//Ajout des utilisateurs
//Ajout des entêtes et des tableaux par user
for(l = 0; l < tabUsers.length; l++){
var firstLine = 1 + (l+1)*10 - 10 + (l + 1) * numProjects - numProjects;
var nbTours = generateUserTimeSheet(tabUsers[l], firstLine, currentMonthSheet, nbDays, semaine);
prjLines = 2;
//Ajout des projets par user
for(m = 0; m < numProjects; m++){
addProject(tabProjectsLibs[m], firstLine + 5 + m, currentMonthSheet, prjLines, numProjects);
prjLines++;
}
}
semaine += nbTours;
}
}

My guess would be that removing these cleanup lines should do the trick.
currentMonthSheet.clear();
currentMonthSheet.clearFormats();
try{
currentMonthSheet.deleteColumns(2, cols - nbDays );
}catch(e){
//Logger.log("erreur : " + e);
}
try{
currentMonthSheet.deleteRows(2, rows - 3);
}catch(e){
//Logger.log("erreur : " + e);
}

Related

Is it possible to get a variable or localStorage value to insert in a Web SQL code?

I've created just a simple code to simulate a virtual store with HTML, Web SQL & Javascript language and my question is: Is it possible to get a variable or localStorage value to insert in a Web SQL code?
I just need to change the code number "100013" below by a variable or localStorage item.
var bdd = openDatabase("bdLojaVirtual", "2.0", "LojaVirtual", 2000000);
var mostrar;
var button = document.getElementById("pesquisar");
button.onclick = function consultarProduto() {
var produto = document.getElementById("codigo").value;
produto = produto;
localStorage.setItem("Item selecionado", produto);
}
bdd.transaction(function (selecionar) {
var produto = localStorage.getItem("Item selecionado");
selecionar.executeSql ('SELECT nome FROM produto WHERE codigo = 100013', [],
function (selecionar, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
mostrar = "<p><b>" + results.rows.item(i).nome + "</b></p>";
document.querySelector('#aqui').innerHTML += mostrar;
}
}, null);
});
The whole project is at https://github.com/jmlJunior/portifolioPessoal
After some research I got it: I've just replaced the code number "100013" by "?" and "[]" by "[produto]" and it works well.
bdd.transaction(function (selecionar) {
var produto = localStorage.getItem("Item selecionado");
selecionar.executeSql ('SELECT nome FROM produto WHERE codigo = ?', [produto],
function (selecionar, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
mostrar = "<p><b>" + results.rows.item(i).nome + "</b></p>";
document.querySelector('#aqui').innerHTML += mostrar;
}
}, null);
});

call method with param in an other method

I'm trying to learn Vue.js and I have a problem.
How can I add the handler "addRowHandlers" in the function addUpHandler ?
I made a pagination system and when I turn the page 1, I lost my handler on the .
It's a basic system. I'm not making a new database request, I use a twig variable which contain all my datas
addUpHandler: function(){
//let up = document.getElementById('up');
//let pageA = 1
const text = document.getElementById('textSearchByName')
if(text.value != ""){
this.pageT += 1
return searchByName(pageT)
}
let myTab = document.getElementById("myTab")
myTab.innerHTML = ""
this.pageA++;
for(let i=(this.pageA-1)*10;i<this.pageA*10;i++){
let dist = segments[i]['distance']/1000
myTab.innerHTML += "<tr v-on:click='addRowHandlers($event)'><td>"+segments[i]['name']+"</td><td>"+segments[i]['nbSegment']+"</td><td>"+dist.toFixed(2)+"km</td><td>"+segments[i]['total_elevation_gain']+"m</td><td>"+segments[i]['average_grade']+"%</td><tr>"
}
},
addRowHandlers: function(event){
this.clearMap();
var td = event.currentTarget.getElementsByTagName("td").length
var cell = event.currentTarget.getElementsByTagName("td")[0]; //get le premier td de la ligne
var polyline = cell.firstElementChild.value;
var idSeg = cell.firstElementChild.nextElementSibling.value
let distance = event.currentTarget.getElementsByTagName("td")[2]
distance = distance.firstElementChild.value
this.getStreams(idSeg, distance, myChart)
var coordonnee = L.Polyline.fromEncoded(polyline).getLatLngs();
L.polyline(
coordonnee,
{
color: 'red',
weight: 2
}
).addTo(map)
},
regards
PS: SOrry for my english

multiple loops google app script

I am currently working in GAS to create and optimize a search function based on multiple criteria.
I have code that works, but it is inconsistent on whether or not the function call will time-out before the search is completed.
//Top level function to run the sub-level OD, ID, End Ring, Pusher, and Bushing Length functions
function toolSearch(od, id, mat) {
var od1 = parseFloat(od);
var id1 = parseFloat(id);
var inc = .25; //change to 0 when standardized bushings are implemented
var passOutput = [];
var failOutput = ["Tooling Unavailable", "Contact CPI Stafford Materials Engineer"];
if (od1 > 49 || id1 > 46)
return failOutput;
//If statement to determine amount of end rings required based on OD shell size and material
if (mat == "Hot Mold" && od < 10)
var qER = 4;
else
qER = 2;
//Initial tooling search
var od2 = toolSearchOD(od1);
var id2 = toolSearchID(id1);
var er = toolSearchER(od2, id2);
var ps = toolSearchPS(od2);
var wall = wallCall(od2, id2);
//return variables must be parsed from strings to integers and decimals
od2 = parseFloat(od2);
id2 = parseFloat(id2);
er = parseInt(er);
ps = parseInt(ps);
wall = parseFloat(wall);
//Remove comments when standardized bushings are implemented
/*if(id>10)
{inc = .5;}
else
{inc = .25;}*/
//If statement to check for pusher and end ring requirments before moving into for loop
if (er < qER || ps < 1) {
//For loop to find OD and ID shells, the required quantity of end rings, and the pusher
for (var i = 0; i < 50; i++) { //Loop is set at 75 in order to prevent 30 second function time out. May need to be adjusted.
od2 += inc;
od2 = toolSearchOD(od2);
od2 = parseFloat(od2);
wall = wallCall(od2, id2);
wall = parseFloat(wall);
er = toolSearchER(od2, id2);
er = parseInt(er);
ps = toolSearchPS(od2);
ps = parseInt(ps);
if (wall > 3) {
id2 -= inc
id2 = toolSearchID(id2);
id2 = parseFloat(id2);
od2 = od1 - inc;
od2 = parseFloat(od2);
er = toolSearchER(od2, id2);
er = parseInt(er);
}
if (er >= qER && ps >= 1)
break;
}
}
//A final check to make sure that the variable is parsed to an integer or decimal
od2 = parseFloat(od2);
id2 = parseFloat(id2);
er = parseInt(er);
ps = parseInt(ps);
wall = parseFloat(wall);
var blength = bLength(mat, od2, id2); //Bushing Length function input/output
//If statement to check if requirements have been met to return the proper information
if (er < qER || ps < 1 || wall > 3) {
return failOutput;
} else {
passOutput = [od2, id2, blength, er, ps, wall];
return passOutput;
}
}
//A final check to make sure that the variable is parsed to an integer or decimal
od2 = parseFloat(od2);
id2 = parseFloat(id2);
er = parseInt(er);
ps = parseInt(ps);
wall = parseFloat(wall);
var blength = bLength(mat,od2, id2); //Bushing Length function input/output
//If statement to check if requirements have been met to return the proper information
if(er < qER || ps < 1 || wall > 3){
Logger.log("FAILURE TO FIND SIZE " + passOutput);
return failOutput;}
else{
passOutput = [od2,id2, blength,er, ps, wall];
return passOutput;}
}
//****************************************************************************************
//Sub-function for searching the shell OD inventory, based on the updated OD from toolSearch
function toolSearchOD(od) {
var range = CacheService.getScriptCache().get('rangeSHOD');//Call to data in cache
range = Utilities.parseCsv(range);//All returns from cache need to be parsed from a CSV format to a horizontal array with a permanent row of zero
var size = lastRow("Shell Inventory");//Call to sub-function to determine index of last row of the sheet with data in it.
var found = 0;
od = parseFloat(od);//A built in check to make sure that the variable is parsed to a decimal
var inc = .25;//change to 0 when standardized bushings are implemented
//Remove comments when standardized bushings are implemented
/*if(od>10)
{var inc = .5;}
else
{inc = .25;}*/
while (found != 1){
for(var j=0;j<size;j++)
{
if(range[0][j] == od){
od = range[0][j];
found = 1;
}
}
if(found != 1)
od+=inc;
}
return od;
}
//****************************************************************************************
//Sub-function for searching the shell OD inventory, based on the updated ID from toolSearch
function toolSearchID(id) {
var range = CacheService.getScriptCache().get('rangeSHID');
range = Utilities.parseCsv(range);
var size = lastRow("Shell Inventory");
var found = 0;
id = parseFloat(id);
var inc = .25;//change to 0 when standardized bushings are implemented
//Remove comments when standardized bushings are implemented
/*if(id>10)
{var inc = .5;}
else
{inc = .25;}*/
while (found != 1){
for(var j=0;j<size;j++)
{
if(range[0][j] == id){
id = range[0][j];
found = 1;
}
}
if(found != 1)
id-=inc;
}
return id;
}
//****************************************************************************************
//Sub-function for searching the end ring inventory, based on the updated ID and OD values from toolSearchID and toolSearchOD.
function toolSearchER(od,id) {
var rangeOD = CacheService.getScriptCache().get('rangeEROD');
var rangeID = CacheService.getScriptCache().get('rangeERID');
var rangeQTY = CacheService.getScriptCache().get('rangeERQTY');
rangeOD = Utilities.parseCsv(rangeOD);
rangeID = Utilities.parseCsv(rangeID);
rangeQTY = Utilities.parseCsv(rangeQTY);
var size = lastRow("End Ring Inventory");
var erQTY = 0;
od = parseFloat(od);
id = parseFloat(id);
for(var j=0;j<size;j++)
{
if(rangeID[0][j] == id && rangeOD[0][j] == od){
erQTY += parseInt(rangeQTY[0][j]);
}
}
return erQTY;
}
//****************************************************************************************
//Sub-function for searching the end ring inventory, based on the updated ID and OD values from toolSearchID and toolSearchOD.
function toolSearchPS(od) {
var rangeQTY = CacheService.getScriptCache().get('rangePSQTY');
var rangeOD = CacheService.getScriptCache().get('rangePSOD');
rangeOD = Utilities.parseCsv(rangeOD);
rangeQTY = Utilities.parseCsv(rangeQTY);
var size = lastRow("Pusher Inventory");
var psQTY = 0;
od = parseFloat(od);
od -= .25;
for(var j=0;j<size;j++)
{
if(rangeOD[0][j] == od){
psQTY = rangeQTY[0][j];
}
}
return psQTY;
}
//****************************************************************************************
//Sub-function to calculate bushing wall size based on updated OD and ID inputs from toolSearch, toolSearchOD, and toolSearchID
function wallCall(od,id){
var wall;
wall = (od-id)/2;
return wall;
}
//****************************************************************************************
//Sub-function that puts all required data into a Google cache for more efficent processing. Cache time limit is 1 hour
function cache(){
var ss = SpreadsheetApp.getActive();
var sheetSH = ss.getSheetByName("Shell Inventory");
var sheetSHL = sheetSH.getRange("F2:F").getValues();
var sheetER = ss.getSheetByName("End Ring Inventory");
var sheetPS = ss.getSheetByName("Pusher Inventory");
var rangeSHOD = sheetSH.getRange("D2:D").getValues();
var rangeSHID = sheetSH.getRange("C2:C").getValues();
var rangeERQTY = sheetER.getRange("H2:H").getValues();
var rangeEROD = sheetER.getRange("C2:C").getValues();
var rangeERID = sheetER.getRange("D2:D").getValues();
var rangePSQTY = sheetPS.getRange("G2:G").getValues();
var rangePSOD = sheetPS.getRange("B2:B").getValues();
CacheService.getScriptCache().put('rangeSHOD',rangeSHOD,3600);
CacheService.getScriptCache().put('rangeSHID',rangeSHID,3600);
CacheService.getScriptCache().put('sheetSHL' ,sheetSHL,3600);
CacheService.getScriptCache().put('rangeERID',rangeERID,3600);
CacheService.getScriptCache().put('rangeEROD',rangeEROD,3600);
CacheService.getScriptCache().put('rangeERQTY',rangeERQTY,3600);
CacheService.getScriptCache().put('rangePSQTY',rangePSQTY,3600);
CacheService.getScriptCache().put('rangePSOD',rangePSOD,3600);
}
//****************************************************************************************
//Sub-function to calculate the index of last row of data for a sheet
function lastRow(sheetName){
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName(sheetName);
var size=sheet.getLastRow();
return size;
}
//****************************************************************************************
//Sub-function to calculate bushing length based on OD and ID shell lengths and type of material
function bLength (mat,od, id){
var rangeID = CacheService.getScriptCache().get('rangeSHID');
var rangeOD = CacheService.getScriptCache().get('rangeSHOD');
var rangeL = CacheService.getScriptCache().get('sheetSHL');
rangeID = Utilities.parseCsv(rangeID);
rangeOD = Utilities.parseCsv(rangeOD);
rangeL = Utilities.parseCsv(rangeL);
var size = lastRow("Shell Inventory");
var lengthID = 0;
var lengthOD = 0;
var blength = 0;
id = parseFloat(id);
od = parseFloat(od);
//Find ID shell length
for(var j=0;j<size;j++)
{
if(rangeID[0][j] == id){
lengthID = rangeL[0][j];
}
}
found = 0;
//Find OD shell length
for(var j=0;j<size;j++)
{
if(rangeOD[0][j] == od){
lengthOD = rangeL[0][j];
}
if(lengthID == 18){
blength = "5 inches *Configuration not recommended*.";}
else if (lengthOD == 18)
blength = "5 inches";
else if(mat == "Hot Mold"){
blength = "6 inches";}
else
blength = "9 inches";
return blength;
}
}
function matType(mat){
var hot = 0;
var matType;
switch (mat){
case 620:
hot = 1;
break;
case 603:
hot = 1;
break;
case 604:
hot = 1;
break;
case 611:
hot = 1;
break;
case 605:
hot = 1;
break;
case 608:
hot = 1;
break;
case 580:
hot = 1;
break;
case 607:
hot = 1;
break;
default:
break;
}
if (hot == 1)
matType = "Hot Mold";
else
matType = "Cold Mold";
return matType;
}
Yes I know it's clunky. The "for" loop requirement is there to keep the script from timing out but it is far from effective and I know there is a better way.
The data is on 3 separate sheets and their is a function that caches all the relevant data to try and limit the amount of calls to the sheet, which helped, but not enough.
How can I make this code more efficient? I need to add more criteria which will require more looping to find the correct set of tooling for a job and I'm afraid this will cause the top level function to exceed the function call time very quickly.

javascript split and for functions

hi im trying to show multiple images with split ans for functios but im having problems:
the php returns a string with links separated by comas and i need to show as image each record this is the code:
var msg 'files/uploads/1688482n.jpg,files/uploads/10904912__n.jpg,files/uploads/10907098_0_o.jpg';
var img = explode(msg)
$('.mensage').html(img);//A el div con la clase msg, le insertamos el mensaje en formato thml
$('.mensage').show('slow');//Mostramos el div.
$("#im").val(""+msg+"");
}
function explode(t) {
var txt = t,
list = txt.split(","),
tt = "";
console.log(list);
for (var i = 0; i < list.length; i++) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+i+"'><br>")); //This gets its place
}
return tt
}
in return im having this in the console:
Resource interpreted as Image but transferred with MIME type text/html:
so how i can display each image right?
the problem is showing like this:
<img style="width:290px;height:190px;" class="img-tm2" src="0">
<img style="width:290px;height:190px;" class="img-tm2" src="1">
Your code has a few bugs. Here is a corrected code:
var msg = 'n.jpg,o.jpg';
var img = explode(msg);
$('.mensage').val(img);//A el div con la clase msg, le insertamos el mensaje en formato thml
$('.mensage').show('slow');//Mostramos el div.
$("#im").html(img);
function explode(txt) {
var list = txt.split(",");
tt = "";
console.log(list);
for (var i = 0; i < list.length; i++) {
tt += "<img style='width:290px;height:190px;' class='img-tm2' src='"+list[i]+"'><br />"; //This gets its place
}
return tt;
}
Trying to enumerate them:
missing semicolons at the end of statements;
var msg = (missing "=");
i instead of list[i];
Why do you print i and not that ?
for (var i = 0; i < list.length; i++) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+list[i]+"'><br>")); //This gets its place
}
use for each instead of for loop.
for each(var url in list) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+url+"'><br>")); //This gets its place
}
return tt
}

ActiveXObject Number of rows counter

I have this piece of code:
function GetData(evt){
var adresses = new Array();
var j = 0;
var excel = new ActiveXObject("Excel.Application");
var fil = document.getElementById("file");
var excel_file = excel.Workbooks.Open(fil.value);
var excel_sheet = excel.Worksheets(1);
for(var i=2;i<500;i++){
var morada = excel_sheet.Range("E"+ i );
var localidade = excel_sheet.Range("C"+ i );
var pais = excel_sheet.Range("A"+i);
adresses[j] = (morada + ", " + localidade + ", " + pais);
j++;
}
for(var k = 0; k<j; k++) {
codeAddress(adresses[k]);
}
}
It receives an excel file and processes the data like I want. The thing is, it is very hard coded.
For instant, in this for:
for(var i=2;i<500;i++)
I am using 500, but I would like to use the number of rows in the sheet. I have already tried a few things like rows.count and whatever and I gave some alerts to see the results, but I just can't find the one who tells me the number of rows.
Anyone know how to do it?
Try that :
excel_sheet.UsedRange.Rows.Count
Does it works ?

Categories

Resources