Repeated local notifications - angularjs

I am developing an application with local notifications with values coming from the database. However, it is repeating the notification with the same value countless times until changing to another.
Example:
1st - "The invoice of house #1 will expire"
2nd - "The invoice of house #1 will expire"
3rd - "The invoice of house #2 will expire"
Any idea what that might be and how to fix it?
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
}
}

I think the problem is in the function that execute calculateDif();
You can also create an array of your articles that you have already notified, for example notifiedHouses = []
and check if the id is already notified using .some
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5 && !this.notifiedHouses.some( item => item.idHouse === idHouse )) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
const house = {idHouse: idHouse}
this.notifiedHouses.push(house);
}
}

Related

.setTimestamp not working with an embed being edited with a loop

I have this embed:
var msgArr = [];
var embed = new Discord.MessageEmbed()
.setTitle('Foo')
.setDescription('Bar')
.setTimestamp();
message.channel.send(embed).then(sentMessage => {
msgArr.push(sentMessage);
});
Which is then edited:
embed = new Discord.MessageEmbed()
.setTitle('Bar')
.setDescription('Foo')
.setTimestamp();
msgArr[0].edit(embed);
This editing process is repeated multiple times on a loop:
var counter = 0;
const frequency = 30000;
setInterval(function () {
if (counter++ % 2 == 0) {
embed = new Discord.MessageEmbed()
.setTitle('Bar')
.setDescription('Foo')
.setTimestamp();
msgArr[0].edit(embed);
} else {
embed = new Discord.MessageEmbed()
.setTitle('Foo')
.setDescription('Bar')
.setTimestamp();
msgArr[0].edit(embed);
}
}, frequency);
(Basically the title and the description switch between 'Foo' and 'Bar' every 30 seconds, with a .setTimestamp included)
Now, what happens when I run this is that the .setTimestamp will work fine for the first minute or 2, then it starts to 'lag' behind the actual time. Can anyone help me figure out the reason for this?
Full Code (Yes there have been some parts cut out, but there are related to API things that have no effect on the embed part):
// Some code is commented out due to requests you have made, it should be obvious which code this is. I haven't cleaned up the commented out code, therefore be warned there will be some variables that aren't in this.
const Discord = require('discord.js');
// Below is normally not constant
const itemAmount = 6;
module.exports = {
name: 'command',
cooldown: 1,
description: 'Test Description',
execute(message) {
function sendEmbeds(channel1, channel2) {
message.client.channels.cache.get(channel1).bulkDelete(8);
for (let i = 0; i < 1; i++) {
let now = new Date();
let embed = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can **buy** with `Bits` and then **sell** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some url')
.addFields(
{ name: 'Information:', value: 'Buy Price: `1500 Bits`\n Sell Price: `250000 Coins` \n Coins per Bit Spent: `250 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
// Next if statement is api related, but since it's important to the embed it'll stay
if (itemAmount >= 5) {
embed.setTitle(i + 1 + '. **HARD TO SELL**: Item');
}
message.client.channels.cache.get(channel1).send(embed).then(sentMessage => {
msgArr.push(sentMessage);
});
}
message.client.channels.cache.get(channel2).bulkDelete(5);
for (let i = 0; i < 1; i++) {
let now = new Date();
var craftableEmbed = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can craft by **buying** `' + craftables[craft[i][0]]["amountNeeded"] + ' ' + craftables[craft[i][0]]["itemNeeded"]["name"] + '` from the lowest BIN, buying `' + craftables[craft[i][0]]["bitsItem"] + '` with `Bits` and then **selling** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some thumbnail')
.addFields(
{ name: 'Information:', value: 'Bits Buy Price: `1200 Bits` \n Item Buy Price: `500000 Coins` \n Sell Price Per Crafted Item: `600000 Coins` \n Profit Per Craft: `746889 Coins` \n Coins per Bit Spent: `153.6 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
message.client.channels.cache.get(channel2).send(craftableEmbed).then(sentMessage => {
msgArrCraft.push(sentMessage);
});
}
}
function editEmbeds() {
for (let i = 0; i < 1; i++) {
let now = new Date();
console.log(now);
let embedNew = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can **buy** with `Bits` and then **sell** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some thumbnail')
.addFields(
{ name: 'Information:', value: 'Buy Price: `1500 Bits`\n Sell Price: `250000 Coins` \n Coins per Bit Spent: `250 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
if (itemAmount >= 5) {
embedNew.setTitle(i + 1 + '. **HARD TO SELL**: Item');
}
msgArr[i].edit(embedNew).then(newEmbed => {
msgArr[i] = newEmbed;
console.log(now, 'edited');
});
}
for (let i = 0; i < 1; i++) {
let now = new Date();
console.log(now);
let craftableEmbedNew = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can craft by **buying** `' + craftable[craft[i][0]]["amountNeeded"] + ' ' + craftable[craft[i][0]]["itemNeeded"]["name"] + '` from the lowest BIN, buying `' + craftable[craft[i][0]]["bitsItem"] + '` with `Bits` and then **selling** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some thumbnail')
.addFields(
{ name: 'Information:', value: 'Bits Buy Price: `1200 Bits` \n Item Buy Price: `500000 Coins` \n Sell Price Per Crafted Item: `600000 Coins` \n Profit Per Craft: `746889 Coins` \n Coins per Bit Spent: `153.6 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
msgArrCraft[i].edit(craftableEmbedNew).then(newEmbed => {
msgArr[i] = newEmbed;
console.log(now, 'edited');
});
}
}
var msgArr = [];
var msgArrCraft = [];
setTimeout(() => {
// Embed
// The bot uses 2 channels, if you are testing this be warned that it is coded to delete 8 messages in the first channel, and 5 messages in the second. (Replace the channel IDs with the ones you are testing in)
sendEmbeds('ChannelID1', 'ChannelID2');
}, 15000);
var counter = 0;
const frequency = 30000;
setInterval(function () {
// Normally this if statement has API related code, this is omitted here therefore it seems useless.
if (counter++ % 2 == 0) {
editEmbeds();
}
else {
editEmbeds();
}
}, frequency);
},
};
If you would like the COMPLETE full code (included a ton of API related things) feel free to ask.

How to map and send emails to specific users who don't meet a certain criteria in Javascript/GAS

I am new in Javascript and bit by bit I have used resources here on StackOverflow to build on a project that uses external API to get time entries for users from the 10k ft project management system. I have finally have different functions together as follows:
Calls for user details which includes user_id
Get the time entries and sums up for every user who's approval has a value (pending or approval) in a specific date range. Those without approval will be ignored in the summation and their total entries left at 0.
My challenge now is to have only those with 0 as total hours of time entries receive emails to update their time entries. This code doesn't seem to select only those with 0 and send emails specifically to them. I will appreciate any pointers and/or assistance. after sending the email, this should be recorded on Google sheet
var TKF_URL = 'https://api.10000ft.com/api/v1/';
var TKF_AUTH = 'auth'
var TKF_PGSZ = 2500
var from = '2020-01-20'
var to = '2020-01-26'
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + TKF_AUTH
}
};
function getUsers() {
var userarray = [];
var lastpage = false;
var page = 1;
do {
// gets 10kft data
var users = read10k_users(page);
// writes data from current page to array
for (var i in users.data) {
var rec = {};
// pushing of mandatory data
rec.id = users.data[i].id;
rec.display_name = users.data[i].display_name;
rec.email = users.data[i].email;
userarray.push(rec);
}
// checks if this is the last page (indicated by paging next page link beeing null
if (users.paging.next != null) {
lastpage = false;
var page = page + 1;
} else {
lastpage = true;
}
}
while (lastpage == false);
return (userarray);
return (userarray);
}
function read10k_users(page) {
var endpoint = 'users?';
var url = TKF_URL + endpoint + 'per_page=' + TKF_PGSZ + '&auth=' + TKF_AUTH + '&page=' + page;
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response);
//Logger.log(json.data)
return (json);
}
function showTimeData() {
var users = getUsers()
var time_array = [];
for (var i = 0; i < users.length; i++) {
// Logger.log(users[i].id)
var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH + '&per_page=' + TKF_PGSZ;
var response = UrlFetchApp.fetch(url, options);
var info = JSON.parse(response.getContentText());
var content = info.data;
var total_hours = 0;
for (var j = 0; j < content.length; j++) {
if (content[j].approvals.data.length > 0) {
total_hours += content[j].hours;
}
}
Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + ' ' + 'total hours: ' + total_hours+ ' ' + 'Email: ' + users[i].email)
}
}
function sendMail(showTimeData){
var emailAddress = user.email;
var message = 'Dear ' + user.display_name + 'Please update your details in the system'
var subject = ' Reminder';
MailApp.sendEmail(emailAddress, subject, message);
}
I was able to get a solution for this as follows:
for (var j = 0; j < content.length; j++) {
if (content[j].approvals.data.length > 0) {
total_hours += content[j].hours;
}
}
Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + ' ' + 'total hours: ' + total_hours + ' ' + 'Email: ' + users[i].email)
if (total_hours == 0) {
sendMail(users[i])
}
}
}
function sendMail(user) {
var emailAddress = user.email;
var message = 'Dear ' + user.display_name + 'Please update your details in the system'
var subject = ' Reminder';
MailApp.sendEmail(emailAddress, subject, message);
}

Loop over Array inside Loop

based on this Mongoose embedded documents / DocumentsArrays id
i try to implement a condition in a loop inside a loop. At the end, the new "tosave" Comments Object should contain the _id from the BlogPost based on "where a_id = b_id".
I use node,express and mongoose.
I have a multi row form with multiple BlogPosts and a Blogpost can have multiple Comments.
On the Backend, i have 2 Arrays -> BlogPosts and Comments like this:
BlogPosts: [{ a_id: '1', name: 'name1' },
{ a_id: '2', name: 'name2' },
{ a_id: '3', name: 'name3' }],
Comments: [{ b_id: '1', name: 'comment for BlogPost name1' },
{ b_id: '1', name: 'other comment for BlogPost name1' },
{ b_id: '3', name: 'comment for BlogPost name3' }],
I need the _id from a Blogpost Document inside every Comment, to reference between Comments and Blogposts.
I loop over the BlogPosts like this:
var new_post_to_save = [];
for(var i=0; i<req.body.blogposts.length;i++) {
var newpost = new BlogPost();
console.log('blogpost nr : ' + [i] + ' has new _id: ' + newpost._id );
newpost.name = req.body.blogposts[i].name,
newpost.a_id = req.body.blogposts[i].a_id
new_post_to_save.push(newpost);
},
This is working fine. I get a new Array "new_post_to_save", witch i can save easy.
Now i try to loop inside BlogPosts to give every Comment the _id Field from the new created "newpost" Object.
What i try - but it failed.. It matches all Comments to all BlogPosts.
var new_post_to_save = [];
var new_comment_to_save = [];
for(var i=0; i<req.body.blogposts.length;i++) {
var newpost = new BlogPost();
console.log('blogpost nr : ' + [i] + ' has new _id: ' + newpost._id );
newpost.name = req.body.blogposts[i].name,
newpost.a_id = req.body.blogposts[i].a_id
// here a loop to create x Comments with the _id from newpost and
// the condition: IF a_id = b_id
// then create new Comment and get die _id from his Blogpost
for(var f=0; f<req.body.comments.length;f++) {
if (newpost.a_id = req.body.comments[f].b_id)
console.log(' Yea ! Comment ' + [f] + ' matches Blogpost Nr. ' + [i]);
var newcomment = new CommentModel();
newcomment.id_newpost = newpost._id,
newcomment.name = req.body.comments[f].name,
newcomment.b_id = req.body.comments[f].b_id,
}; // end if
}; // end for
new_comment_to_save.push(newcomment);
new_post_to_save.push(newpost);
}, // end for
This is my first question here.
Any ideas ? Thanks so much
I am not familair with Mongoose, just looking at your code, seems you have a little mistake in code: position of: new_comment_to_save.push(newcomment); it should be in the if because only when they match you want them added..
var new_post_to_save = [];
var new_comment_to_save = [];
for(var i=0; i<req.body.blogposts.length;i++) {
var newpost = new BlogPost();
console.log('blogpost nr : ' + [i] + ' has new _id: ' + newpost._id );
newpost.name = req.body.blogposts[i].name,
newpost.a_id = req.body.blogposts[i].a_id
// here a loop to create x Comments with the _id from newpost and
// the condition: IF a_id = b_id
// then create new Comment and get die _id from his Blogpost
for(var f=0; f<req.body.comments.length;f++) {
if (newpost.a_id = req.body.comments[f].b_id)
console.log(' Yea ! Comment ' + [f] + ' matches Blogpost Nr. ' + [i]);
var newcomment = new CommentModel();
newcomment.id_newpost = newpost._id,
newcomment.name = req.body.comments[f].name,
newcomment.b_id = req.body.comments[f].b_id,
new_comment_to_save.push(newcomment);
}; // end if
}; // end for
new_post_to_save.push(newpost);
}, // end for

Variable in Parsley Error Message not updating

I have a form where I need to show an "expected value" for feedback on why the specific field is not validating.
This expected value changes with different input, like so:
var varOne = $('#id_iNeedToCheck').val() ;
var varTwo = $('#id_iNeedToCheck2').val() ;
var expectedValue = ( varOne / 28) + (varTwo / 10) + 8 ;
$('#id_iNeedToCheck').change(function(){
return [varOne = $('#id_iNeedToCheck').val(),expectedValue = (varOne / 28) + (varTwo / 10) + 8] ;
});
The custom validation then looks like this:
window.Parsley.addValidator('myValidator', {
validateNumber: function(value) {
if (value > expectedValue) {
return value - expectedValue <= 7 ;
}
else {
return expectedValue - value <= 7;
}
},
requirementType: 'string',
messages: {
en: 'Your input differs too much from what we expect, we expect ' + expectedValue + ', and your input can not be 7 more or 7 less than this value.'
}
});
inside
messages: {
en: 'Your input differs too much from what we expect, we expect ' + expectedValue + ', and your input can not be 7 more or 7 less than this value.'
}
this value is never updated, as it seems this value is only parsed once, while the custom validator is constantly reparsed and works "as intended".
How do I make sure this message is updated/reparsed as "expectedValue" keeps changing?
Dealing with interdepencencies is tricky. You could inspire yourself from this example.

Trouble populating Mongo Database from Nodejs

The following json order has shipping, payment, orderProduct as elements. I am trying to access the individual elements using the code below:
{
"shipping": "{\"nickName\":\"gsfsdfdf\",\"firstName\":\"gsfsdfdf\",\"lastName\":\"gsfsdfdf\",\"addressLine1\":\"gsfsdfdf\",\"addressLine2\":\"gsfsdfdf\",\"city\":\"gsfsdfdf\",\"country\":\"gsfsdfdf\",\"province\":\"gsfsdfdf\",\"postalCode\":\"gsfsdfdf\",\"phone\":\"gsfsdfdf\",\"email\":\"gsfsdfdf\",\"shippingInstruction\":\"gsfsdfdfgsfsdfdfgsfsdfdfgsfsdfdf\"}",
"payment": "{\"cardType\":\"Visa\",\"cardNumber\":\"11111111111111111111\",\"expMonth\":\"3\",\"expYear\":\"2019\",\"csc\":\"111\"}",
"orderProduct": "[{\"productId\":\"594fce45734d1d24b915a41f\",\"quantity\":1}]",
"deliveryDate": "2017-07-07T04:00:00.000Z"
}
I am using the code below to access the various elements of the json data:
router.post('/order/add', function (req, res) {
console.log('order = ' + req.body.order);
var newOrder = req.body.order;
console.log('shipping = ' + newOrder.shipping);
console.log('payment = ' + newOrder.payment);
console.log('orderProduct = ' + newOrder.orderProduct);
console.log('deliveryDate = ' + newOrder.deliveryDate);
var order = new Order({
shipping: newOrder.shipping,
payment: newOrder.payment,
orderProduct: newOrder.orderProduct,
deliveryDate: newOrder.deliveryDate,
});
console.log("created server order = " + order);
return res.json(200, order);
})
But the shipping, payment, orderProduct, deliveryDAte are return undefined.

Resources