Not able to update firebase reference values , using promises = > promise.all - javascript

I have two references in firebase :
1. products
2. nutritions
Scenario is when user complete a list of choices, their nutrition values inside nutritions(2) reference should be picked from the product catalogue maintained under products reference(1)
Here is the code I am trying to work with but not sure what I am missing, Below code only update first product nutrition content. I am new with Angular2 and firebase.
//capturing promises
let promises = Object.keys(choices)
.map(k => {
return new Promise((resolve, reject) => {
this.updateNutrtion(choices[k].choice,resolve,reject);
});
});
//promise.all
Promise.all(promises).then((object)=> console.log(object));
updateNutrtion(choice,res,rej){
//logic to get the nutritions
return new Promise((res,rej)=>{
firebase.database().ref('/products/' + choice).once('value',function(snapshot){
snapshot.forEach(function(child){
var consumeDay;
var today = new Date().toISOString();
var year = today.split("-")[0];
var month = today.split("-")[1];
var day = ( today.split("-")[2] ).split("T")[0]
consumeDay = day + '-' + month + '-' + year;
// update firebase nutrition
firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + child.ref.key).once('value',function(nutrition){
firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + child.ref.key).update({
unit : child.val().unit,
value : (nutrition.val()!=null) ? (nutrition.val().value + child.val().value) : (child.val().value)
})
})
return false;
})
}).then((key)=>{
res(key);
});
})
}
Please assist where I am going wrong.

solved it.. In case if this help someone else , posting code below.
//handelling promises over an array
let promises = Object.keys(choices)
.map(k => {
var val =this.updateAllNutritions(choices[k].choice)
.then(function(values) {
var consumeDay;
var today = new Date().toISOString();
var year = today.split("-")[0];
var month = today.split("-")[1];
var day = ( today.split("-")[2] ).split("T")[0]
consumeDay = day + '-' + month + '-' + year;
// console.log('all done', values); // [snap, snap, snap]
Object.keys(values)
.map(j=>{
var unit = firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + values[j].valueOf).child('unit')
var value = firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + values[j].valueOf).child('value')
unit.transaction(function(currentUnit){
return values[j].unit;
});
value.transaction(function(currentValue){
return currentValue + values[j].value;
})
})
});
});
//update nutritions async function
updateAllNutritions(choice){
return firebase.database().ref('/products/' + choice).once('value').then(function(snapshot){
var nutritions = [];
var consumeDay;
var today = new Date().toISOString();
var year = today.split("-")[0];
var month = today.split("-")[1];
var day = ( today.split("-")[2] ).split("T")[0]
consumeDay = day + '-' + month + '-' + year;
snapshot.forEach(function(childSnapshot){
var promise = firebase.database().ref('/nutritions/' + firebase.auth().currentUser.uid + '/' + consumeDay + '/' + childSnapshot.ref.key).once('value').then(function(snap){
var snapNull = null;
if(snap.val()!=null){
// console.log("currentvalue" + snap.val().value);
snapNull = snap.val().value
}
let promisedettrue = {
unit : childSnapshot.val().unit,
value : childSnapshot.val().value,
valueOf : childSnapshot.ref.key,
isNodenull : false,
currentValue : snapNull
};
let promisedetfalse = {
unit : childSnapshot.val().unit,
value : childSnapshot.val().value,
valueOf : childSnapshot.ref.key,
isNodenull : true,
};
if(snap.val()==null){
return promisedetfalse;
}else{
return promisedettrue;
}
},function(error){
// The Promise was rejected.
console.error(error);
});
nutritions.push(promise);
});
return Promise.all(nutritions);
},function(error){
// The Promise was rejected.
console.error(error);
})
}

Related

Get the closest date to current date from a web table containing dates in a date column

A web table having 10 columns with fist(0) column as date, from the list of dates I have to get the closest date to current date. Depending on the index of that date row, I need to get the amount in the last(9)th column.
const getRowIndex = () => {
let idx;
cy.log('tbody tr td:first-child block is running');
cy.get('tbody tr td:first-child').each(($el, index) => {
cy.wrap($el).then($span => {
const todaysDate2 = new Date();
const spanText = $span.text();
//cy.log('todaysDate2 value : ' + todaysDate2);
cy.log('First time Date : ' + spanText);
//cy.log(todaysDate);
const parts = spanText.split('/');
const d = new Date(parts[2], parts[1] - 1, parts[0]);
if (d.getTime() <= todaysDate2.getTime()) {
if (d.getTime() > closestDate || closestDate === undefined) {
closestDate = d.getTime();
idx = index;
cy.log('first time rowIndex: ' + idx);
cy.log('first updated closest date to: ' + closestDate);
cy.log('first the value of $el is : ' + $el);
cy.log(
'first the value of spanText and index: ' + spanText + idx,
); // gets date
if (idx > 0) return idx;
}
cy.log('index value of idx is :' + idx);
}
});
});
cy.log('index value of idx is :' + idx);
return idx;
};
// ---------------------------------------------
cy.log('tbody tr block is running');
cy.get(`tbody tr`)
.each(($el2, index, list) => {
// lines 187 to 200 using $el.innerHtml or something like that and return $el
const todaysDate2 = new Date();
const spanText = $el2.text();
//cy.log('spanText value in second loop :' + spanText);
//cy.log('second time todaysDate2 value : ' + todaysDate2);
cy.log('second time list : ' + index); // number of the row
//cy.log('Second time Date : ' + spanText.split('£')); // this is getting the date
cy.log('todaysDate2 value is : ' + todaysDate2);
const parts = spanText.split('/');
cy.log('value of parts : ' + parts); // + parts.values()
const d = new Date(parts[2], parts[1] - 1, parts[0]);
cy.log('value of d variable is :' + d);
debugger;
if (d.getTime() <= todaysDate2.getTime()) {
cy.log('updated closest date to first time: ' + closestDate);
cy.log('the value of $el2 is first time : ' + spanText);
if (d.getTime() > closestDate || closestDate === undefined) {
closestDate = d.getTime();
cy.log('updated closest date to second time: ' + closestDate);
cy.log('the value of $el is second time : ' + $el2);
// #ts-ignore
if ($el2 > 1) return false;
return $el2;
}
}
})
.find(`td:nth-child(9)`)
.then($span => {
cy.log('getting the amount :' + $span.text());
});
// --------------------------------------------------
cy.wrap(
cy.get('tbody tr:nth-child(' + getRowIndex() + ') td:nth-child(9)'),
).then($span => {
// eslint-disable-next-line max-lines
cy.log('getting the amount :' + $span.get(span.text()));
});
},
);
Result:
Got all the dates with each row data but unable to break once reached the closest date.

Cypress type error when given string returned from cypress command

I have the following cypress command function created,
Cypress.Commands.add("gen_date", () => {
var now_dt = new Date(Date.now());
var dte =
("0" + now_dt.getDate()).slice(-2) +
("0" + now_dt.getHours()).slice(-2) +
("0" + now_dt.getMinutes()).slice(-2) +
("0" + now_dt.getSeconds()).slice(-2) +
("00" + now_dt.getMilliseconds()).slice(-3);
return dte;
});
I call this command in the following test file ,
it("see if test string generated in input", () => {
let o = cy.gen_date();
cy.get("input[id=\"inputid\"]")
.as("inputinput")
.type(o)
.type("{enter}");
I expect o to be a string, but instead in cypress tests I get the error, cy.type() can only accept string or number and you passed in [object, Object]
Could someone point me in the right dirction
Cypress custom commands return a Chainable which passes the result forward to the next linked command, so you can access it by nesting
cy.gen_date().then(dt => {
cy.get("input[id=\"inputid\"]")
.as("inputinput")
.type(dt)
.type("{enter}");
})
or use plain JS function instead of a custom command
const gen_date = () => {
var now_dt = new Date(Date.now());
var dte = ("0" + now_dt.getDate()).slice(-2) +
("0" + now_dt.getHours()).slice(-2) +
("0" + now_dt.getMinutes()).slice(-2) +
("0" + now_dt.getSeconds()).slice(-2) +
("00" + now_dt.getMilliseconds()).slice(-3);
return dte;
};
let o = gen_date();
cy.get("input[id=\"inputid\"]")
.as("inputinput")
.type(o)
.type("{enter}");
Adding the function globally:
in /cypress/support/index.js
Cypress.gen_date = () => {
var now_dt = new Date(Date.now());
var dte = ("0" + now_dt.getDate()).slice(-2) +
("0" + now_dt.getHours()).slice(-2) +
("0" + now_dt.getMinutes()).slice(-2) +
("0" + now_dt.getSeconds()).slice(-2) +
("00" + now_dt.getMilliseconds()).slice(-3);
return dte;
};
in the test
let o = Cypress.gen_date();

How is this variable still NULL

I'm in the process of writing a CasperJS script to automate a search form and capture the subsequent page. However, the search form goes to a loading splash page first until data arrives. So i added the waitForSelector function which seems to be working for some of my pages, but others return the variable name as NULL. How can that be if it is truly "waiting" for that element to be on the DOM?
casper.each(searchPages,function(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
},function(){
console.log("Search page timed-out.");
},20000);
});
});
I was able to solve this by creating a recursive function if the element is still not available. Now i'm having a memory issue though, new question here => CasperJS running out of memory
casper.each(searchPages,function(casper,index){
loadSearch(casper,index);
});
function loadSearch(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
if (this.exists('#destinationForPackage')){
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
}else{
console.log("Still doesn't exist...retry");
loadSearch(casper,index);
}
},function(){
console.log("Search page timed-out.");
},20000);
});
}

javascript - how to create countdown to date and time from sql server database?

It's my first time using a countdown in javascript so I have researched a little about this topic and I found some interesting links: "how to countdown to a date" and "https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/", but my question is if I want to get data and time from the database, how can I do that? E.g.: I have a table Event with ID,Event,StartDate,StartTime and EndTime. How can I change from this: "var end = new Date('02/19/2012 10:1 AM');" from the first link or this: "Schedule the Clock Automatically" from the second to countdown time until event with the most recent time and date, and so on. Please keep in mind that I'm a total nooby so please bear with me. Sorry for any misspelling. Thank you!
Update:
This is the controller part: [HttpGet]
public JsonResult GetEvent(int Id)
{
BOL1.IMS2Entities db = new BOL1.IMS2Entities();
var ev = from e in db.tbl_Event
where e.ID == Id
select e;
//return Json(ev.FirstOrDefault(), JsonRequestBehavior.AllowGet);
return Json(Id, JsonRequestBehavior.AllowGet);
}
and this is the scripting part:
<script>
function GetEvent() {
debugger;
$.ajax({
type: "GET",
url: "Home/GetEvent",
data: { Id: ID },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
var tbl_Event.StartDate = 'yyyy-MM-dd hh:hh:hh';
//var ServerDate_Time = '2017-02-17 10:45:00';
//console.log(CompareDateTime(ServerDate_Time));
console.log(CompareDateTime(tbl_Event.StartDate + tbl_Event.StartTime))
//function CompareDateTime (ServerDateTime){
function CompareDateTime (tbl_Event.StartDate + tbl_Event.StartTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
}
</script>
assuming your datetime you are getting int tbl_Event.StartDate + tbl_Event.StartTime = 2017-02-17 10:45:00
this will go for your..
var ServerDate_Time = '2017-02-17 10:45:00';
console.log(CompareDateTime(ServerDate_Time));
function CompareDateTime (ServerDateTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
Hope this helps....
Edit after your Edit ....
Updated code...
For Controller --
[HttpGet]
public JsonResult GetEvent(int id)
{
using (IMS2Entities ObjEntities = new IMS2Entities())
{
var ev = from e in ObjEntities.tblEvents
where e.id == id
select e;
return Json(ev.ToList(), JsonRequestBehavior.AllowGet);
}
}
JavaScript code for this
<script>
$(function () {
GetEvent(); // this will call GetEvent function once your DOM is ready, you can call this function on button click or anywhere as per your need.
function GetEvent() {
$.ajax({
type: "GET",
url: "/Home/GetEvent",
data: { Id: '1' }, // '1' is id for my sql database record which is passing to controller to bring back record from server.
success: function (result) {
// result will be collection of list return form server, since you are using id criteria it will always have only 1 record unless you have id as foreign key or something not primary/unique.
// I'm using only first instance of result for demo purpose, you can modify this as per your need.
alert(CompareDateTime(result[0].StartDateTime.substr(6))); // this will alert your true or false, as per I guess this will always return false, as your current date time will never match sql datetime. Still for your requirement.
},
error: function (response) {
alert(response);
}
});
}
function CompareDateTime (ServerDateTimeFormat){
// Convert ServerDateTimeFormat for Comparision
var ServerdateString = ServerDateTimeFormat;
var ServerCurrentTime = new Date(parseInt(ServerdateString));
var Servermonth = ('0' + (ServerCurrentTime.getMonth() + 1)).slice(-2)
var Serverday = ('0' + (ServerCurrentTime.getDate())).slice(-2)
var Serveryear = ServerCurrentTime.getFullYear();
var Serverhours = ('0' + (ServerCurrentTime.getHours())).slice(-2)
var Servermin = ('0' + (ServerCurrentTime.getMinutes())).slice(-2)
var Serversec = ('0' + (ServerCurrentTime.getSeconds())).slice(-2)
var Serverdate = Serveryear + "-" + Servermonth + "-" + Serverday + " " + Serverhours + ":" + Servermin + ":" + Serversec;
// Current Date Time for Comparision
var currentTime = new Date();
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if (date == Serverdate) {
return true;
}else {
return false;
}
}
});
</script>
Please make sure you put reference for JQuery before ... tag.
This is fully working example.. :)

Unique ID that gets a date in specific format?

I have code that will generate a random unique id.. but is there a way I can edit this code so that it grabs a date in a specific way like yyyy-mm-dd-0001. the last 4 digits I want it to add 1 each time the generateid button is clicked. so it will change to 0002. Here is the current code I have. Is there a function that can grab the date automatically?
var counter = 0000;
function Counter() {
if((document.getElementById("generateid").clicked == true)
{
Counter++
return counter;
}
}
function Month() {
var m = new Date();
var mm = m.getMonth() + 1;
if (mm < 10) {
mm = '0' + mm;
return mm;
}
}
function Year() {
var y = new Date();
var yy = y.getFullYear();
return yy;
}
function Day() {
var d = new Date();
var dd = d.getDate();
return dd;
}
//generate id
function guidGenerator() {
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + Counter);
return theID;
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator();
document.getElementById("generateid").disabled = true;
}
You can use the following object:
var idGenerator = {
seq: 0,
generateId: function () {
this.seq++;
return (new Date()).toISOString().substring(0, 10) + '-' + ('000' + this.seq).substr(-4)
}
}
after declaration like this, try
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + idGenerator.generateId();
document.getElementById("generateid").disabled=true;
}
If you are asking for a way to keep track of how many times an ID is generated by all your site visitors using javascript alone then, no it is not possible without tying in some back end to keep track. However, the following code will do what you ask per visitor.
jsfiddle
var ttlIds = 0;
function guidGenerator() {
var S4 = function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + S4());
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator().toString().toUpperCase();
//document.getElementById("generateid").disabled=true;
ttlIds++;
if(ttlIds < 10){
ttlIds_formatted = '000'+ttlIds;
}else if(ttlIds < 100){
ttlIds_formatted = '00'+ttlIds;
}else if(ttlIds < 1000){
ttlIds_formatted = '0'+ttlIds;
}
d = new Date();
var funkydate = d.getFullYear() +'-' + (d.getMonth()+1) + '-' + d.getDate() + '-' + ttlIds_formatted;
document.getElementById("funkydate").value = funkydate;
}

Categories

Resources