Limit used time to the length of the day/ time slot

This commit is contained in:
Jonas Lochmann 2020-08-24 02:00:00 +02:00
parent 15b576a2d7
commit 9730d13b2e
No known key found for this signature in database
GPG key ID: 8B8C9AEE10FA5B36
2 changed files with 10 additions and 4 deletions

View file

@ -26,6 +26,9 @@ export const getRoundedTimestamp = () => {
return now - (now % (1000 * 60 * 60 * 24 * 2 /* 2 days */))
}
const dayLengthInMinutes = MinuteOfDay.LENGTH
const dayLengthInMs = dayLengthInMinutes * 1000 * 60
export async function dispatchAddUsedTime ({ deviceId, action, cache }: {
deviceId: string
action: AddUsedTimeAction
@ -63,7 +66,7 @@ export async function dispatchAddUsedTime ({ deviceId, action, cache }: {
if (action.timeToAdd !== 0) {
// try to update first
const [updatedRows] = await cache.database.usedTime.update({
usedTime: Sequelize.literal(`usedTime + ${action.timeToAdd}`) as any,
usedTime: Sequelize.literal(`MAX(0, MIN(usedTime + ${action.timeToAdd}, ${dayLengthInMs}))`) as any,
lastUpdate: roundedTimestamp
}, {
where: {
@ -82,7 +85,7 @@ export async function dispatchAddUsedTime ({ deviceId, action, cache }: {
familyId: cache.familyId,
categoryId: categoryId,
dayOfEpoch: action.dayOfEpoch,
usedTime: action.timeToAdd,
usedTime: Math.min(action.timeToAdd, dayLengthInMs),
lastUpdate: roundedTimestamp,
startMinuteOfDay: MinuteOfDay.MIN,
endMinuteOfDay: MinuteOfDay.MAX

View file

@ -64,9 +64,12 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache }:
// tslint:disable-next-line:no-inner-declarations
async function handle (start: number, end: number) {
const lengthInMinutes = (end - start) + 1
const lengthInMs = lengthInMinutes * 1000 * 60
// try to update first
const [updatedRows] = await cache.database.usedTime.update({
usedTime: Sequelize.literal(`usedTime + ${item.timeToAdd}`) as any,
usedTime: Sequelize.literal(`MAX(0, MIN(usedTime + ${item.timeToAdd}, ${lengthInMs}))`) as any,
lastUpdate: roundedTimestampForUsedTime
}, {
where: {
@ -85,7 +88,7 @@ export async function dispatchAddUsedTimeVersion2 ({ deviceId, action, cache }:
familyId: cache.familyId,
categoryId: item.categoryId,
dayOfEpoch: action.dayOfEpoch,
usedTime: item.timeToAdd,
usedTime: Math.min(item.timeToAdd, lengthInMs),
lastUpdate: roundedTimestampForUsedTime,
startMinuteOfDay: start,
endMinuteOfDay: end