Issues with back-to-back reservations, catching standalone charges & brake between bookings

This commit is contained in:
Senad Uka
2019-12-06 06:10:19 +01:00
parent 43c4214a23
commit 983c08ff36
6 changed files with 421 additions and 181 deletions

View File

@@ -57,6 +57,8 @@ const csvParserErrors = {
const officeRnDAPIErrors = { const officeRnDAPIErrors = {
FAILED_TO_FETCH_MEMBERS: 'Failed to fetch members', FAILED_TO_FETCH_MEMBERS: 'Failed to fetch members',
FAILED_TO_FETCH_BOOKINGS: 'Failed to fetch booking reservations', FAILED_TO_FETCH_BOOKINGS: 'Failed to fetch booking reservations',
FAILED_TO_CREATE_BOOKINGS: 'Failed to create booking reservations',
FAILED_TO_DELETE_BOOKINGS: 'Failed to delete booking reservations',
FAILED_TO_FETCH_FEES: 'Failed to fetch existing fees from ORD', FAILED_TO_FETCH_FEES: 'Failed to fetch existing fees from ORD',
FAILED_TO_FETCH_PLANS: 'Failed to fetch plans from ORD', FAILED_TO_FETCH_PLANS: 'Failed to fetch plans from ORD',
FAILED_TO_DELETE_FEES: 'Failed to delete fees in ORD', FAILED_TO_DELETE_FEES: 'Failed to delete fees in ORD',

View File

@@ -359,7 +359,7 @@ const getLockEntryForReservation = (reservation, nextReservation) => {
const getEntriesBetween = (fromTimestamp, toTimestamp, resourceId) => { const getEntriesBetween = (fromTimestamp, toTimestamp, resourceId) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!fromTimestamp || !toTimestamp || !resourceId){ if (!resourceId){
resolve([]); resolve([]);
}else { }else {
const andTimestampFilters = []; const andTimestampFilters = [];

View File

@@ -146,7 +146,7 @@ const getIncidentsFromChanges = (changes) => {
reservationsForAdditionalCheck.push(reservationId); reservationsForAdditionalCheck.push(reservationId);
} }
} else { } else {
console.log('\t\tNo'); // console.log('\t\tNo');
// Reservation moved to another day // Reservation moved to another day
// Add cancellation charge // Add cancellation charge
const chargeFee = oldReservationLength * reservationHourlyRate * BOOKING_CHANGE_PERCENTAGE_CHARGE / 100; const chargeFee = oldReservationLength * reservationHourlyRate * BOOKING_CHANGE_PERCENTAGE_CHARGE / 100;

View File

@@ -49,10 +49,13 @@ const checkBookingChanges = () => {
Promise.all(asyncActions) Promise.all(asyncActions)
.then((asyncActionResults) => { .then((asyncActionResults) => {
const changes = asyncActionResults[1]; const changes = asyncActionResults[1];
// console.log(changes);
bulkWriteChanges(changes) bulkWriteChanges(changes)
.then(() => { .then(() => {
getIncidentsFromChanges(changes) getIncidentsFromChanges(changes)
.then(({incidents, reservationsForAdditionalCheck}) => { .then(({incidents, reservationsForAdditionalCheck}) => {
// console.log('=====INCIDENTS=====');
// console.log(incidents);
bulkWriteBookingChangeIncidents(incidents) bulkWriteBookingChangeIncidents(incidents)
.then(() => { .then(() => {
getReservationsIncidentsForRemoval(reservationsForAdditionalCheck) getReservationsIncidentsForRemoval(reservationsForAdditionalCheck)

View File

@@ -51,6 +51,7 @@ const insertUnscheduledIncidents = (incidents) => {
totalChargeFee, totalChargeFee,
unlockTimestamp, unlockTimestamp,
lockTimestamp, lockTimestamp,
deleted: false
}; };
asyncJobs.push(db.unscheduledIncident.findOrCreate({ asyncJobs.push(db.unscheduledIncident.findOrCreate({
@@ -62,7 +63,6 @@ const insertUnscheduledIncidents = (incidents) => {
bookingEnd: end, bookingEnd: end,
unlockTimestamp, unlockTimestamp,
lockTimestamp, lockTimestamp,
deleted: false
}, },
defaults: {...incidentForDB}, defaults: {...incidentForDB},
})); }));
@@ -95,6 +95,7 @@ const insertUnlockedIncidents = (incidents) => {
unlockTimestamp, unlockTimestamp,
incidentLevel, incidentLevel,
incidentLevelPrice, incidentLevelPrice,
deleted: false
}; };
asyncJobs.push(db.unlockedIncident.findOrCreate({ asyncJobs.push(db.unlockedIncident.findOrCreate({
@@ -106,7 +107,6 @@ const insertUnlockedIncidents = (incidents) => {
bookingEnd: end, bookingEnd: end,
unlockTimestamp, unlockTimestamp,
incidentLevel, incidentLevel,
deleted: false
}, },
defaults: {...incidentForDB}, defaults: {...incidentForDB},
})); }));
@@ -177,8 +177,8 @@ const setUnlockedIncidentsLevel = (incidents) => {
formattedIncident.incidentLevel = unlockedIncidentLevelsPrices.UNLOCKED_0.title; formattedIncident.incidentLevel = unlockedIncidentLevelsPrices.UNLOCKED_0.title;
formattedIncident.incidentLevelPrice = unlockedIncidentLevelsPrices.UNLOCKED_0.price; formattedIncident.incidentLevelPrice = unlockedIncidentLevelsPrices.UNLOCKED_0.price;
} else { } else {
const lastIncidentTime = moment.utc(memberLastIncident.incidentTimestamp).startOf('month'); const lastIncidentTime = moment.tz(memberLastIncident.incidentTimestamp, UI_TIMEZONE).startOf('month');
const currentIncidentTime = moment.utc(incident.unlockTimestamp).startOf('month'); const currentIncidentTime = moment.tz(incident.unlockTimestamp, UI_TIMEZONE).startOf('month');
const timeDiff = Math.abs(lastIncidentTime.diff(currentIncidentTime, 'months')); const timeDiff = Math.abs(lastIncidentTime.diff(currentIncidentTime, 'months'));
if (timeDiff >= (parseInt(process.env.UNLOCK_STREAK_REPAIR_AFTER) || 6)){ if (timeDiff >= (parseInt(process.env.UNLOCK_STREAK_REPAIR_AFTER) || 6)){
@@ -238,7 +238,7 @@ const analyseReservation = (reservation) => {
const previousReservationEnd = moment.utc(previousReservation.end); const previousReservationEnd = moment.utc(previousReservation.end);
timeDifferenceFromPreviousReservation = currentReservationStart.diff(previousReservationEnd, 'minutes'); timeDifferenceFromPreviousReservation = currentReservationStart.diff(previousReservationEnd, 'minutes');
} }
const previousReservationIsBackToBack = timeDifferenceFromPreviousReservation < MAX_BACK_TO_BACK_DIFFERENCE; const previousReservationIsBackToBack = timeDifferenceFromPreviousReservation <= MAX_BACK_TO_BACK_DIFFERENCE;
let timeDifferenceBeforeNextReservation = MAX_BACK_TO_BACK_DIFFERENCE + 100; let timeDifferenceBeforeNextReservation = MAX_BACK_TO_BACK_DIFFERENCE + 100;
@@ -246,7 +246,7 @@ const analyseReservation = (reservation) => {
const nextReservationStart = moment.utc(nextReservation.start); const nextReservationStart = moment.utc(nextReservation.start);
timeDifferenceBeforeNextReservation = nextReservationStart.diff(currentReservationEnd, 'minutes'); timeDifferenceBeforeNextReservation = nextReservationStart.diff(currentReservationEnd, 'minutes');
} }
const nextReservationIsBackToBack = timeDifferenceBeforeNextReservation < MAX_BACK_TO_BACK_DIFFERENCE; const nextReservationIsBackToBack = timeDifferenceBeforeNextReservation <= MAX_BACK_TO_BACK_DIFFERENCE;
let timeDifferenceFromUnlockEntry = 0; let timeDifferenceFromUnlockEntry = 0;
if (unlockEntry) { if (unlockEntry) {
@@ -273,9 +273,10 @@ const analyseReservation = (reservation) => {
const totalChargeFeeAfter = timeIntervalsToChargeAfter * UNSCHEDULED_CHARGE_PRICE; const totalChargeFeeAfter = timeIntervalsToChargeAfter * UNSCHEDULED_CHARGE_PRICE;
const chargeAfter = totalChargeFeeAfter > 0; const chargeAfter = totalChargeFeeAfter > 0;
// if (reservation.memberId === '5ce785af422bdd00967fb781') { // const reservationMoment = moment.tz(reservation.start, reservation.timezone);
// if (reservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-11-21 00:00:16+00')) {
// console.log('\r\n\r\n==== ANALYSE RESERVATION ==== '); // console.log('\r\n\r\n==== ANALYSE RESERVATION ==== ');
// console.log('\tStart : ', moment.tz(reservation.start, reservation.timezone).format('DD.MM, HH:mm')); // console.log('\tStart : ', reservationMoment.format('DD.MM, HH:mm'));
// console.log('\tEnd : ', moment.tz(reservation.end, reservation.timezone).format('DD.MM, HH:mm')); // console.log('\tEnd : ', moment.tz(reservation.end, reservation.timezone).format('DD.MM, HH:mm'));
// console.log('\t----------------------------------'); // console.log('\t----------------------------------');
// console.log('\tFirst previous reservation : '); // console.log('\tFirst previous reservation : ');
@@ -366,10 +367,163 @@ const getIncidentData = (reservation) => {
timeIntervalsToChargeAfter, timeIntervalsToChargeAfter,
} = result; } = result;
const incidents = []; const incidents = [];
const incidentsAsyncJobs = [];
const { resourceId } = currentReservation; const { resourceId } = currentReservation;
// 0a. Check for unscheduled use between current and previous reservation // const reservationMoment = moment.tz(currentReservation.start, currentReservation.timezone);
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-11-23 00:00:16+00')) {
// console.log('\r\n\r\n==== ANALYSE RESERVATION [GET INCIDENT DATA] ==== ');
// console.log('\tStart : ', reservationMoment.format('DD.MM, HH:mm'));
// console.log('\tEnd : ', moment.tz(currentReservation.end, currentReservation.timezone).format('DD.MM, HH:mm'));
// console.log('\t----------------------------------');
// console.log('\tFirst previous reservation : is back to back [', previousReservationIsBackToBack ? 'T' : 'F' , ']');
// if (previousReservation) {
// console.log('\t\tStart : ', moment.tz(previousReservation.start, previousReservation.timezone).format('DD.MM, HH:mm'));
// console.log('\t\tEnd : ', moment.tz(previousReservation.end, previousReservation.timezone).format('DD.MM, HH:mm'));
// } else {
// console.log('\t\tNO PREVIOUS RESERVATION');
// }
//
// console.log('\tFirst next reservation : is back to back [', nextReservationIsBackToBack ? 'T' : 'F', ']');
// if (nextReservation) {
// console.log('\t\tStart : ', moment.tz(nextReservation.start, nextReservation.timezone).format('DD.MM, HH:mm'));
// console.log('\t\tEnd : ', moment.tz(nextReservation.end, nextReservation.timezone).format('DD.MM, HH:mm'));
// } else {
// console.log('\t\tNO NEXT RESERVATION');
// }
// console.log('\t----------------------------------');
// if (unlockEntry) {
// console.log('\tUnlock entry : ', moment.tz(unlockEntry.timestamp, reservation.timezone).format('DD.MM, HH:mm'));
// } else {
// console.log('\tUnlock entry : NO UNLOCK ENTRY');
// }
// if (lockEntry) {
// console.log('\tLock entry : ', moment.tz(lockEntry.timestamp, reservation.timezone).format('DD.MM, HH:mm'));
// } else {
// console.log('\tLock entry : NO LOCK ENTRY');
// }
// }
//**********************
const emptyReservation = {
reservationId: null,
start: null,
end: null,
};
// 1. Check if member entered before reservation start time
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\r\n\r\nChecking if member entered before reservation start time :');
// console.log('\tunlockEntry : ', unlockEntry && unlockEntry.timestamp ? unlockEntry.timestamp : 'NO UNLOCK ENTRY');
// console.log('\tCharge before : ', chargeBefore);
// console.log('\tThere is prev. res : ', previousReservationIsBackToBack);
// }
if (unlockEntry && chargeBefore && !previousReservationIsBackToBack) {
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\tIncident : YES');
// }
incidents.push({
incidentType: incidentType.UNSCHEDULED_INCIDENT_BEFORE_RESERVATION,
reservation,
unlockTimestamp: unlockEntry.timestamp,
lockTimestamp: null,
memberId: reservation.memberId,
resourceId: reservation.resourceId,
chargePrice: UNSCHEDULED_CHARGE_PRICE,
timeIntervalsToCharge: timeIntervalsToChargeBefore,
totalChargeFee: totalChargeFeeBefore,
});
}else{
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\tIncident : NO');
// }
}
// 2. Check if member left after reservation end time
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\r\n\r\nChecking if member left after reservation end time :');
// console.log('\tlockEntry : ', lockEntry && lockEntry.timestamp ? lockEntry.timestamp : 'NO LOCK ENTRY');
// console.log('\tCharge after : ', chargeAfter);
// console.log('\tThere is res after : ', nextReservationIsBackToBack);
// }
if (lockEntry && chargeAfter && !nextReservationIsBackToBack) {
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\tIncident : YES');
// }
incidents.push({
incidentType: incidentType.UNSCHEDULED_INCIDENT_AFTER_RESERVATION,
reservation,
unlockTimestamp: null,
lockTimestamp: lockEntry.timestamp,
memberId: reservation.memberId,
resourceId: reservation.resourceId,
chargePrice: UNSCHEDULED_CHARGE_PRICE,
timeIntervalsToCharge: timeIntervalsToChargeAfter,
totalChargeFee: totalChargeFeeAfter,
});
}else{
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\tIncident : NO');
// }
}
// 3. Check if member forgot to lock the door
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\r\n\r\nChecking if member left unlocked door :');
// console.log('\tunlockEntry : ', unlockEntry && unlockEntry.timestamp ? unlockEntry.timestamp : 'NO UNLOCK ENTRY');
// console.log('\tlockEntry : ', lockEntry && lockEntry.timestamp ? lockEntry.timestamp : 'NO LOCK ENTRY');
// console.log('\tThere is res before: ', previousReservationIsBackToBack);
// console.log('\tThere is res after : ', nextReservationIsBackToBack);
// }
let forgotToLockAsyncCheck;
if (!lockEntry && !nextReservationIsBackToBack){
if (unlockEntry){
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\tIncident : YES [#1]');
// }
incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_RELATED_WITH_RESERVATION,
unlockTimestamp: unlockEntry.timestamp,
memberId: reservation.memberId,
resourceId: unlockEntry.resourceId,
reservation: reservation && reservation.dataValues ? reservation.dataValues : emptyReservation,
});
} else {
// No lock entry, no unlock entry and no reservation after this one
// This is either :
// 1. Last reservation in block of N reservations
// 1a. Member locked before entering this reservation
// 1b. Member forgot to lock the door <<< Only this is real incident
// 2. One reservation, but member never entered
if (previousReservationIsBackToBack){
// To ensure that this is last reservation in block (there is previous but no next reservation back to back)
// Now, just check if member actually locked before in the reservation time
forgotToLockAsyncCheck = getLastEntryForReservation(reservation);
forgotToLockAsyncCheck
.then((lastEntry) => {
if (lastEntry && lastEntry.event === doorLockEvents.USER_UNLOCKED){
// if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-12-01 00:00:16+00')) {
// console.log('\tIncident : YES [#2]');
// }
incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_RELATED_WITH_RESERVATION,
unlockTimestamp: lastEntry.timestamp,
memberId: lastEntry.memberId,
resourceId: lastEntry.resourceId,
reservation: reservation && reservation.dataValues ? reservation.dataValues : emptyReservation,
});
}
})
.catch((error) => reject(error));
}
}
}
// 4. Check for unscheduled use between current and previous reservation
const analysePreviousJob = []; const analysePreviousJob = [];
if (previousReservation && !previousReservationIsBackToBack){ if (previousReservation && !previousReservationIsBackToBack){
analysePreviousJob.push(analyseReservation(previousReservation)); analysePreviousJob.push(analyseReservation(previousReservation));
@@ -377,7 +531,6 @@ const getIncidentData = (reservation) => {
analysePreviousJob.push(undefined); analysePreviousJob.push(undefined);
} }
incidentsAsyncJobs.push(
Promise.all(analysePreviousJob) Promise.all(analysePreviousJob)
.then(([previousReservationResults]) => { .then(([previousReservationResults]) => {
let fromTimestamp; let fromTimestamp;
@@ -385,6 +538,38 @@ const getIncidentData = (reservation) => {
if (previousReservationResults){ if (previousReservationResults){
const previousReservationLockEntry = previousReservationResults.lockEntry; const previousReservationLockEntry = previousReservationResults.lockEntry;
const previousReservationUnlockEntry = previousReservationResults.unlockEntry;
//Special check for bookings with break between
if (previousReservation &&
!previousReservationIsBackToBack &&
previousReservation.memberId === currentReservation.memberId &&
previousReservationUnlockEntry && !previousReservationLockEntry &&
!unlockEntry && lockEntry //current reservation unlock / lock entries
) {
const unlockMoment = previousReservation.end ? moment.utc(previousReservation.end) : null;
const lockMoment = currentReservation.start ? moment.utc(currentReservation.start) : null;
if (unlockMoment && lockMoment){
const timeDifference = lockMoment.diff(unlockMoment, 'minutes');
const timeIntervalsToCharge = Math.floor(timeDifference / UNSCHEDULED_TIME_RESOLUTION);
const totalChargeFee = timeIntervalsToCharge * UNSCHEDULED_CHARGE_PRICE;
if (timeIntervalsToCharge > 0) {
incidents.push({
incidentType: incidentType.UNSCHEDULED_INCIDENT_STANDALONE,
reservation: emptyReservation,
unlockTimestamp: previousReservation.end,
lockTimestamp: currentReservation.start,
memberId: currentReservation.memberId,
resourceId,
chargePrice: UNSCHEDULED_CHARGE_PRICE,
timeIntervalsToCharge,
totalChargeFee,
});
}
}
}
fromTimestamp = previousReservationLockEntry && previousReservationLockEntry.timestamp ? fromTimestamp = previousReservationLockEntry && previousReservationLockEntry.timestamp ?
previousReservationLockEntry.timestamp : previousReservation.end; previousReservationLockEntry.timestamp : previousReservation.end;
@@ -396,27 +581,56 @@ const getIncidentData = (reservation) => {
unlockEntry.timestamp : reservation.start; unlockEntry.timestamp : reservation.start;
} }
incidentsAsyncJobs.push( // Let's skip this if previous reservation is back-to-back
getEntriesBetween(fromTimestamp, toTimestamp, resourceId) let getEntriesAsyncCheck;
if (previousReservation && previousReservationIsBackToBack){
//Skip
}else{
getEntriesAsyncCheck = getEntriesBetween(fromTimestamp, toTimestamp, resourceId);
getEntriesAsyncCheck
.then((entriesBetween) => { .then((entriesBetween) => {
incidentsAsyncJobs.push( // const reservationMoment = moment.tz(currentReservation.start, currentReservation.timezone);
new Promise((resolve, reject) => { // if (currentReservation.memberId === '5ce785af422bdd00967fb781' && reservationMoment.isAfter('2019-11-23 00:00:16+00')) {
// console.log('\r\n\r\n==== ANALYSE RESERVATION [GET INCIDENT DATA] ==== ');
// console.log('\tStart : ', reservationMoment.format('DD.MM, HH:mm'));
// console.log('\tEnd : ', moment.tz(currentReservation.end, currentReservation.timezone).format('DD.MM, HH:mm'));
// console.log('\t----------------------------------');
// console.log('\tFirst previous reservation : is back to back [', previousReservationIsBackToBack ? 'T' : 'F', ']');
// if (previousReservation) {
// console.log('\t\tStart : ', moment.tz(previousReservation.start, previousReservation.timezone).format('DD.MM, HH:mm'));
// console.log('\t\tEnd : ', moment.tz(previousReservation.end, previousReservation.timezone).format('DD.MM, HH:mm'));
// } else {
// console.log('\t\tNO PREVIOUS RESERVATION');
// }
//
// console.log('\tFirst next reservation : is back to back [', nextReservationIsBackToBack ? 'T' : 'F', ']');
// if (nextReservation) {
// console.log('\t\tStart : ', moment.tz(nextReservation.start, nextReservation.timezone).format('DD.MM, HH:mm'));
// console.log('\t\tEnd : ', moment.tz(nextReservation.end, nextReservation.timezone).format('DD.MM, HH:mm'));
// } else {
// console.log('\t\tNO NEXT RESERVATION');
// }
//
// console.log('\t--------------------');
//
// console.log('\tFrom timestamp : ', fromTimestamp ? moment.tz(fromTimestamp, UI_TIMEZONE).format('DD.MM, HH:mm') : '-');
// console.log('\tTo timestamp : ', toTimestamp ? moment.tz(toTimestamp, UI_TIMEZONE).format('DD.MM, HH:mm') : '-');
// console.log('\t--------------------');
// }
let pairUnlockEntry = null; let pairUnlockEntry = null;
let pairLockEntry = null; let pairLockEntry = null;
//Inspect all entries and insert detected incidents
entriesBetween.forEach((entry) => { entriesBetween.forEach((entry) => {
// console.log('\tEvent : ', entry.event);
// console.log('\tEvent : ', entry.timestamp ? moment.tz(entry.timestamp, UI_TIMEZONE).format('DD.MM, HH:mm') : '-');
if (entry && entry.event){ if (entry && entry.event){
switch(entry.event){ switch(entry.event){
case doorLockEvents.USER_UNLOCKED: case doorLockEvents.USER_UNLOCKED:
if (!pairUnlockEntry){ if (!pairUnlockEntry){
pairUnlockEntry = entry; pairUnlockEntry = entry;
}else{ }else{
const emptyReservation = {
reservationId: null,
start: null,
end: null,
};
incidents.push({ incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE, incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE,
reservation: emptyReservation, reservation: emptyReservation,
@@ -432,11 +646,7 @@ const getIncidentData = (reservation) => {
case doorLockEvents.USER_LOCKED: case doorLockEvents.USER_LOCKED:
if (pairUnlockEntry && !pairLockEntry){ if (pairUnlockEntry && !pairLockEntry){
pairLockEntry = entry; pairLockEntry = entry;
const emptyReservation = {
reservationId: null,
start: null,
end: null,
};
const unlockMoment = moment.utc(pairUnlockEntry.timestamp); const unlockMoment = moment.utc(pairUnlockEntry.timestamp);
const lockMoment = moment.utc(pairLockEntry.timestamp); const lockMoment = moment.utc(pairLockEntry.timestamp);
@@ -458,12 +668,6 @@ const getIncidentData = (reservation) => {
}); });
} }
}else{ }else{
const emptyReservation = {
reservationId: null,
start: null,
end: null,
};
incidents.push({ incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE, incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE,
reservation: emptyReservation, reservation: emptyReservation,
@@ -486,114 +690,50 @@ const getIncidentData = (reservation) => {
} }
} }
}); });
resolve(null);
})); if (pairUnlockEntry){
incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE,
reservation: emptyReservation,
unlockTimestamp: pairUnlockEntry.timestamp,
memberId: pairUnlockEntry.memberId,
resourceId,
});
pairLockEntry = null;
pairUnlockEntry = null;
}
//Now wait also for "forgotToLockAsyncCheck" to finish
// Promise.all([forgotToLockAsyncCheck])
// .then(() => {
// resolve(incidents);
// })
// .catch(error => reject(error));
}) })
.catch((error) => reject(error))); .catch((error) => reject(error))
})
.catch((error) => reject(error)));
// 1. Check if member entered before reservation start time
// console.log('\r\n\r\nChecking if member entered before reservation start time :');
// console.log('\tunlockEntry : ', unlockEntry && unlockEntry.timestamp ? unlockEntry.timestamp : 'NO UNLOCK ENTRY');
// console.log('\tCharge before : ', chargeBefore);
// console.log('\tThere is prev. res : ', previousReservationIsBackToBack);
if (unlockEntry && chargeBefore && !previousReservationIsBackToBack) {
// console.log('\tIncident : YES');
incidents.push({
incidentType: incidentType.UNSCHEDULED_INCIDENT_BEFORE_RESERVATION,
reservation,
unlockTimestamp: unlockEntry.timestamp,
lockTimestamp: null,
memberId: reservation.memberId,
resourceId: reservation.resourceId,
chargePrice: UNSCHEDULED_CHARGE_PRICE,
timeIntervalsToCharge: timeIntervalsToChargeBefore,
totalChargeFee: totalChargeFeeBefore,
});
}else{
// console.log('\tIncident : NO');
} }
// 2. Check if member left after reservation end time //Now wait for "forgotToLockAsyncCheck", and possible "getEntriesBetween" to finish
// console.log('\r\n\r\nChecking if member left after reservation end time :'); Promise.all([forgotToLockAsyncCheck, getEntriesAsyncCheck])
// console.log('\tlockEntry : ', lockEntry && lockEntry.timestamp ? lockEntry.timestamp : 'NO LOCK ENTRY');
// console.log('\tCharge after : ', chargeAfter);
// console.log('\tThere is res after : ', nextReservationIsBackToBack);
if (lockEntry && chargeAfter && !nextReservationIsBackToBack) {
// console.log('\tIncident : YES');
incidents.push({
incidentType: incidentType.UNSCHEDULED_INCIDENT_AFTER_RESERVATION,
reservation,
unlockTimestamp: null,
lockTimestamp: lockEntry.timestamp,
memberId: reservation.memberId,
resourceId: reservation.resourceId,
chargePrice: UNSCHEDULED_CHARGE_PRICE,
timeIntervalsToCharge: timeIntervalsToChargeAfter,
totalChargeFee: totalChargeFeeAfter,
});
}else{
// console.log('\tIncident : NO');
}
// 3. Check if member forgot to lock the door
// console.log('\r\n\r\nChecking if member left unlocked door :');
// console.log('\tunlockEntry : ', unlockEntry && unlockEntry.timestamp ? unlockEntry.timestamp : 'NO UNLOCK ENTRY');
// console.log('\tlockEntry : ', lockEntry && lockEntry.timestamp ? lockEntry.timestamp : 'NO LOCK ENTRY');
// console.log('\tThere is res before: ', previousReservationIsBackToBack);
// console.log('\tThere is res after : ', nextReservationIsBackToBack);
if (!lockEntry && !nextReservationIsBackToBack){
const emptyReservation = {
reservationId: null,
start: null,
end: null,
};
if (unlockEntry){
// console.log('\tIncident : YES [#1]');
incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_RELATED_WITH_RESERVATION,
unlockTimestamp: unlockEntry.timestamp,
memberId: reservation.memberId,
resourceId: unlockEntry.resourceId,
reservation: reservation && reservation.dataValues ? reservation.dataValues : emptyReservation,
});
} else {
// No lock entry, no unlock entry and no reservation after this one
// This is either :
// 1. Last reservation in block of N reservations
// 1a. Member locked before entering this reservation
// 1b. Member forgot to lock the door <<< Only this is real incident
// 2. One reservation, but member never entered
if (previousReservationIsBackToBack){
// To ensure that this is last reservation in block (there is previous but no next reservation back to back)
// Now, just check if member actually locked before in the reservation time
incidentsAsyncJobs.push(
getLastEntryForReservation(reservation)
.then((lastEntry) => {
if (lastEntry && lastEntry.event === doorLockEvents.USER_UNLOCKED){
// console.log('\tIncident : YES [#2]');
incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_RELATED_WITH_RESERVATION,
unlockTimestamp: lastEntry.timestamp,
memberId: lastEntry.memberId,
resourceId: lastEntry.resourceId,
reservation: reservation && reservation.dataValues ? reservation.dataValues : emptyReservation,
});
}
})
.catch((error) => reject(error)));
}
}
}
Promise.all(incidentsAsyncJobs)
.then(() => { .then(() => {
resolve(incidents); resolve(incidents);
}) })
.catch((error) => reject(error)); .catch(error => reject(error));
})
.catch(error => reject(error));
//
// Promise.all(incidentsAsyncJobs)
// .then(() => {
// // console.log('\tDone with Async jobs for reservation ');
// // console.log('\t\tStart : ', reservationMoment.format('DD.MM, HH:mm'));
// // console.log('\t\tEnd : ', moment.tz(currentReservation.end, currentReservation.timezone).format('DD.MM, HH:mm'));
//
// setTimeout(() => {resolve(incidents)}, 10000);
// // resolve(incidents);
// })
// .catch((error) => reject(error));
}) })
.catch((error) => reject(error)); .catch((error) => reject(error));

View File

@@ -5,7 +5,7 @@ const moment = require('moment-timezone');
const Op = require('sequelize').Op; const Op = require('sequelize').Op;
const { API } = require('../../helpers/api'); const { API } = require('../../helpers/api');
const { officeRnDAPIErrors, MAX_BACK_TO_BACK_DIFFERENCE } = require('../../constants/constants'); const { officeRnDAPIErrors, MAX_BACK_TO_BACK_DIFFERENCE, UI_TIMEZONE } = require('../../constants/constants');
const fetchAllBookings = () => { const fetchAllBookings = () => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -14,24 +14,119 @@ const fetchAllBookings = () => {
const cleanedBookingReservations = []; const cleanedBookingReservations = [];
const bookingData = result && result.data ? result.data : []; const bookingData = result && result.data ? result.data : [];
const bookingsToCreate = [];
const bookingIdsToRemove = [];
bookingData.forEach(fullBookingEntry => {
if (!fullBookingEntry){
return;
}
const fees = fullBookingEntry.fees ? fullBookingEntry.fees : [];
if (fees.length > 1){
// Recurring booking, let's create new booking
const member = fullBookingEntry.member ? fullBookingEntry.member : null;
const office = fullBookingEntry.office ? fullBookingEntry.office : null;
const resourceId = fullBookingEntry.resourceId ? fullBookingEntry.resourceId : null;
const team = fullBookingEntry.team ? fullBookingEntry.team : null;
const organization = fullBookingEntry.organization ? fullBookingEntry.organization : null;
const plan = fullBookingEntry.plan ? fullBookingEntry.plan : null;
const timezone = fullBookingEntry.timezone ? fullBookingEntry.timezone : UI_TIMEZONE;
const source = 'admin';
const startMoment = fullBookingEntry && fullBookingEntry.start && fullBookingEntry.start.dateTime ?
moment.utc(fullBookingEntry.start.dateTime) : null;
const endMoment = fullBookingEntry && fullBookingEntry.end && fullBookingEntry.end.dateTime ?
moment.utc(fullBookingEntry.end.dateTime) : null;
fees.forEach(fee => {
const dateMoment = fee.date ? moment.utc(fee.date) : null;
if (startMoment && endMoment && dateMoment){
const yearPart = dateMoment.year();
const monthPart = dateMoment.month();
const dayPart = dateMoment.date();
const newStartMoment = startMoment.clone().tz(fullBookingEntry.timezone).year(yearPart).month(monthPart).date(dayPart);
const newEndMoment = endMoment.clone().tz(fullBookingEntry.timezone).year(yearPart).month(monthPart).date(dayPart);
bookingsToCreate.push({
start: {
dateTime: newStartMoment.toISOString()
},
end: {
dateTime: newEndMoment.toISOString()
},
team,
member,
resourceId,
office,
source,
timezone,
organization,
plan
})
}
});
bookingIdsToRemove.push(fullBookingEntry['_id']);
}
});
//Here we now have possible bookings to create and then load again "check Booking changes"
if (bookingIdsToRemove.length > 0){
//First delete, wait until operation is done, than create bookings (to avoid conflicting date/time)
API.delete('bookings/?silent', { data: bookingIdsToRemove })
.then(() => {
//Now, insert new bookings
API.post('bookings/?silent', bookingsToCreate)
.then(() => {
//And fetch again all bookings
resolve(fetchAllBookings());
})
.catch((error) => {
console.log(officeRnDAPIErrors.FAILED_TO_CREATE_BOOKINGS);
console.log('Details : ', error);
reject(officeRnDAPIErrors.FAILED_TO_CREATE_BOOKINGS);
});
})
.catch(error => {
console.log(officeRnDAPIErrors.FAILED_TO_DELETE_BOOKINGS);
console.log('Details : ', error);
reject(officeRnDAPIErrors.FAILED_TO_DELETE_BOOKINGS);
});
}else{
bookingData.forEach((fullBookingEntry) => { bookingData.forEach((fullBookingEntry) => {
const fees = fullBookingEntry && fullBookingEntry.fees ? fullBookingEntry.fees : []; const fees = fullBookingEntry && fullBookingEntry.fees ? fullBookingEntry.fees : [];
const firstFee = fees.length > 0 && fees[0].fee ? fees[0].fee : undefined; const firstFee = fees.length > 0 && fees[0].fee ? fees[0].fee : undefined;
const hourlyRate = firstFee && firstFee.price ? firstFee.price : 0; const hourlyRate = firstFee && firstFee.price ? firstFee.price : 0;
const startMoment = fullBookingEntry && fullBookingEntry.start && fullBookingEntry.start.dateTime ?
moment.utc(fullBookingEntry.start.dateTime) : null;
const endMoment = fullBookingEntry && fullBookingEntry.end && fullBookingEntry.end.dateTime ?
moment.utc(fullBookingEntry.end.dateTime) : null;
// console.log('\r\n\r\nStart : ', startMoment.clone().tz(fullBookingEntry.timezone).format('DD.MM. HH:mm'), '[', startMoment.toISOString(),']');
// console.log('End : ', endMoment.clone().tz(fullBookingEntry.timezone).format('DD.MM. HH:mm'), '[', endMoment.toISOString(), ']');
// console.log('Fees : ');
if (startMoment && endMoment){
cleanedBookingReservations.push({ cleanedBookingReservations.push({
reservationId: fullBookingEntry['_id'], reservationId: fullBookingEntry['_id'],
memberId: fullBookingEntry.member, memberId: fullBookingEntry.member,
officeId: fullBookingEntry.office, officeId: fullBookingEntry.office,
resourceId: fullBookingEntry.resourceId, resourceId: fullBookingEntry.resourceId,
start: fullBookingEntry.start.dateTime, start: startMoment.toISOString(),
end: fullBookingEntry.end.dateTime, end: endMoment.toISOString(),
timezone: fullBookingEntry.timezone, timezone: fullBookingEntry.timezone,
canceled: fullBookingEntry.canceled || false, canceled: fullBookingEntry.canceled || false,
hourlyRate, hourlyRate,
}); });
}
}); });
resolve(cleanedBookingReservations); resolve(cleanedBookingReservations);
}
}) })
.catch((error) => { .catch((error) => {
console.log(officeRnDAPIErrors.FAILED_TO_FETCH_BOOKINGS); console.log(officeRnDAPIErrors.FAILED_TO_FETCH_BOOKINGS);