Reset values every day with mongoDB - javascript

I need to clean every day a values on mongo db
That´s like ---> Reset every day when its 00AM
AND
Reset every end of month
const totalOfDay = 123
const totalOfMonth = 12344
every day reset the totalDay, and every end of month reset totalMonth
I did this on my front-end, but with the app close this dont work, and the server will be online everytime, so that´s (I THINK) more easier

Related

Find how many slots I can use within the given period of time

I am working on the booking / reservation project and faced some interesting issue.
The point of the project is to determine if there is any time slot available for reservation within the given period of time (12:00 - 15:00).
Also, it supports the N amount of rooms / tables allowed to be reserved. (for example, maximum it could be reserved up to 30 rooms)
Currently, data is stored in the mysql db, with the structure:
id, start_time, end_time and some another payload
Firstly, I was sure that I can do a simple sql select do determine overlaps and count the amount of rows returned
sql-query looks like this:
SELECT * FROM reservations WHERE ((start_time < '${end_time}' AND start_time >= '${start_time}')
OR (start_time <= '${start_time}' AND end_time >= '${end_time}') OR (end_time > '${start_time}')
${start_time} - time recieved from the front-end
start_time - column name in the database table.
But eventually I end up with the huge bug.
Timeline is horizontal, each rectangle represents one of the created reservations.
Empty slot means that there is an empty table / room that could be reserved.
But using this select in order to check available table for time range from 16:00 until 19:00 - query returns more than 50 rows and the if > N_amount replies that there is no available table / room for that time available (but that's obviously not true).
example row:id=1, start_time=2022-08-06 12:00:00, end_time=2022-08-06 15:00:00
Every time slot is rounded to **:30 or **:00 minutes
Any ideas on how to change the query / logic in order to achieve the desired behaviour?
When i understand you right, you are trying to get all reservations between a start time and a end time.
(start_time < '${end_time}' AND start_time >= '${start_time}')
This query gives you every reservation with a start time before the end oft the timeslot and a start time after the start of the timeslot
(start_time <= '${start_time}' AND end_time >= '${end_time}')
With that query you are recieving every reservation with a start_time before the timeslot and with a end time after the timeslot
(end_time > '${start_time}')
With that query you are recieving every reservation whith a end time after the start time requested from the frontend, which is giving you every reservation with a end time that is after the start time requested. I think that this is the main problem.
Now firstly please take a look at this page https://www.stackhawk.com/blog/node-js-sql-injection-guide-examples-and-prevention/ which is giving you important informations about SQL-Injection. Your code has a major security problem! In Node.JS a fix for that can look like this:
connection.query('SELECT * FROM sheet where id = ?', [id], (err, rows) => {
//code
});
To get better results i would recommend to fetch all reservations that only have a start time in that timeslot and then putting the whole reservation into your table.
SELECT * FROM reservations WHERE ((reservations.start_time >= *start_time* AND reservations.start_time < *end_time*) OR (reservations.end_time > *start_time* AND reservations.end_time <= *end_time*))
With that query you are recieving all reservations that have a start time in that range or a end time in that range which should give you good results.
Please remember to replace my ** fillings with ? as shown in the example before
You did not give enough information.
Keeping it simple each row in the SQL table represents the room/table
and date being reserved.
No one starts on one day and holds it until the next day. For example
start time = 23:00 for an hour and a half, crossing midnight into the
next day.
Rather than ask the user for date, start time, and end time, I would ask for the date(s) of service, then give them a matrix of check boxes that represent the slots available for the user to check.
I will assume the SQL table has a row for each room and date where the row columns are: date,room,slot0, ... slot47 (48 half hour slots) assuming 24 hour availability
I would create an object for conversion of time slot number (0-47) to the time slot column name (0-47):
const slots = ['slot0','slot1',...'slot47'];
You calculate the time slot for the first half hour.
Then calc the number of slots needed.
From that you build the query. For a 15:00 start time and 3 slots needed.
15:00 translates to slot29 and 15:30 translates to slot30.
You could use another object to translate the hour to a time slot:<
const hour2slot = {0:[0],1:[2],2:[4]... 23:[46]}
Then translate the minutes :00 and :30 to one or zero.
const minutes = {0:[0], 30:[1]}
So the first time slot:
timeslot1 = hour2slot[hour] + minutetoslot[minutes]
Then build the query with a for loop.
var where = 'WHERE `DATE` = date AND' + slots[timeslot1] + "= ''"
for slot=timeslot1, slot < number_of_slots,slot++){
var where = where + ' AND ' + slots[slot] + "=''"
}
var sql = 'SELECT `room` FROM `table` ' + where + ' LIMIT 1'
I did not check my math or code, but you should get the idea.
The result would be:
SELECT `room` FROM `table` WHERE `slot29` = '' AND `slot30`='' AND `slot31` = '' LIMIT 1
But this would be so much simpler to create a table with the available time slots to be selected by the user.
BTW, I never use SELECT * FROM

How to store birthdays in a database with timezone support?

I am using JavaScript and a PostgreSQL database, I would like to store birthdays and notify users at 12pm in their own timezone, currently I am converting dates from their timezone to my local server time and check every hour to see if a date and time matches
import { parseFromTimeZone } from "date-fns-timezone";
const userInput = "08-11" // day/month
const timeZone = "Europe/Amsterdam"
const date = parseFromTimeZone(`2000-${userInput} 00:00:00`, { timeZone });
// This is what I store in my database
const dateToStore = date.toISOString().slice("2000:".length).split(":")[0];
// This is what I run every hour
await Birthday.find({
where: {
date: new Date().toISOString().slice("year:".length).split(":")[0],
},
});
The problem is that this solution is not very dynamic because if I migrate my server it breaks, my questions are:
How can I store the birthdays? Assume users provide the month, day and time zone
In what interval can / should I check to see if a birthday message should be sent? (00:00) in the user's time zone and specified date
What would that check look like?
I have date-fns available but I do not mind using other libraries
I'd recommend a solution with a account table containing three fields:
birthday, which is of Postgres type date.
timezone, of Postgres type text. Here you'd store something like Europe/Amsterdam, with the important part is that it's something Postgres and your date libraries can all recognize as a time zone.
last_birthday_wish_sent_at of type timestamptz (shorthand for timestamp with time zone, which stores everything internally as UTC).
I've decoupled the birthday date from its timezone because remember that a user's birthday is always the same day anywhere in the world, even if they move around. So if my birthday is August 11th in Amsterdam, it's still August 11th if I move to San Francisco. Storing these components separately would allow you to reconfigure their timezone if they move.
I'd run a cron on the 0th minute of each hour that ran logic something like this (pseudocode, sorry):
for timezone in all timezones:
if > 12 PM in timezone:
for account in accounts in timezone:
if birthday <= today AND (last_birthday_wish_sent_at IS NULL OR last_birthday_wish_sent_at < now() - '1 year):
send birthday wish
set last_birthday_wish_sent_at = now()
The purpose of last_birthday_wish_sent_at is so that you can write an algorithm that's a bit dumber and more resilient (i.e. birthday wishes still get sent even if the cron fails one hour), but still make sure to never double-send a birthday wish for any given year.
It might also be safer to model this as a separate table where you track every birthday wish you've ever sent and the user and year you sent it for. This eliminates any potential for time bugs across year boundaries.
You'd want to model the account selection and filtering in the pseudocode above as SQL so that you're not returning result sets larger than necessary. Something like:
SELECT *
FROM account
WHERE timezone IN ('Europe/Amsterdam', ...)
-- note: actual date comparison a little more complicated than this
-- because you should make sure to compare the month and day components
-- only (probably with the `EXTRACT` function)
AND birthday <= NOW()
AND (
last_birthday_wish_sent IS NULL
OR last_birthday_wish_sent < NOW() - '1 year'::interval
);
And make sure there's appropriate indexes on timezone, birthday, and last_birthday_wish_sent.
You could also tighten up the logic around time zone checks: it's always turning 12 PM somewhere, but it's perfectly predictable as to where that's happening so it's not necessary to check every time zone every time. You could also potentially push this into Postgres and get the whole selection logic packaged up into a single query.

How to get total steps count (pedometer) for current day only (Gear S2)?

Looking for a way to get total steps count for current day only.
Using
tizen.humanactivitymonitor.setAccumulativePedometerListener
I can get accumulativeTotalStepCount which is Accumulative walking and running step count since the device is booted. according to documentation.
But I not need since device is booted, I need since current day started.
You can use the StepDifference Interface object available in which you can find the stepdifference based on timestamps.
You can set the timestamp as when the day starts and get the stepdiffernce which will be the currentday count.

Parse Clouod Code Check If Date Is Today

In my app i want a feature where the user can update their status but i want them to only be able to update it once every 24 hours. Basically i want to take the updatedAt field from parse and check if the change was today in Cloud Code.
I am not very familiar with javascript but her's what i've tried:
https://www.parse.com/questions/compare-date-and-createdat-to-figure-out-the-difference-in-days
How to compare 2 Date fields in Parse Cloud?
I couldn't get to a solution that would basically tell me (beforeSave) if the date is today and allow the user to save/update the field if it isn't.
An example of what i want is WhatsApp that only allowed changing the last seen status on/off once every 24 hours. Also Viber has this feature.
Thanks.
Parse.com supports moment.js
var updatedAt = ... ; // Get updatedAt value of your object
var now = moment();
if (now.diff(updatedAt, 'hours') >= 24) {
// Last update was more than 24 hours ago
}

Day to day counter with Reset button

I'd like to add a counter to my website which counts in days. However I'd also like to add a button where this can be reset back to 0.
After searching I found the below code, and all is needed now is the button for it. I'm no Javascript expert so any help would be great.
I used this code to create the counter:
<script type="text/javascript">
//Set the two dates
var startdate=new Date(2013, 11, 16) //Month is 0-11 in JavaScript
today=new Date()
//Get 1 day in milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((today.getTime()-startdate.getTime())/(one_day))+
" days since your last drink!")
</script>
Is there a way I can include a button to reset the start date to the current date (for example if pressed today it would change from 16th of December 2013 to the 19th of December 2013)
Does anyone have any idea how I would do this? I'm fairly new to javascript so just learning the ropes.
Thanks
Gary
#Jonathan has given a good method of achieving this using cookies.This is what most of the sites use to save your preferences.
Another possible way is that you can make use of database to save the startDate for each user and update it accordingly when the reset button is set.The next time you fetch startDate it will be the updated date.You can save it where you are saving his profile information.
If you have small number of users you can also use xml file to store the startDate information and updating it accordingly.
I would go for database or cookies.
Hope it helps

Categories

Resources