Merge branch 'fix-repeated-booking' into 'master'

Fix repeated booking

See merge request saburly/psihologija!72
This commit was merged in pull request #72.
This commit is contained in:
Bilal Catic
2019-12-05 08:29:30 +00:00
6 changed files with 220 additions and 89 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

@@ -533,92 +533,123 @@ const getIncidentData = (reservation) => {
getEntriesBetween(fromTimestamp, toTimestamp, resourceId) getEntriesBetween(fromTimestamp, toTimestamp, resourceId)
.then((entriesBetween) => { .then((entriesBetween) => {
// 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--------------------');
//
// 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 //Inspect all entries and insert detected incidents
entriesBetween.forEach((entry) => { entriesBetween.forEach((entry) => {
if (entry && entry.event){ // console.log('\tEvent : ', entry.event);
switch(entry.event){ // console.log('\tEvent : ', entry.timestamp ? moment.tz(entry.timestamp, UI_TIMEZONE).format('DD.MM, HH:mm') : '-');
case doorLockEvents.USER_UNLOCKED: if (entry && entry.event){
if (!pairUnlockEntry){ switch(entry.event){
pairUnlockEntry = entry; case doorLockEvents.USER_UNLOCKED:
}else{ if (!pairUnlockEntry){
const emptyReservation = { pairUnlockEntry = entry;
reservationId: null, }else{
start: null, const emptyReservation = {
end: null, reservationId: null,
}; start: null,
end: null,
};
incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE,
reservation: emptyReservation,
unlockTimestamp: pairUnlockEntry.timestamp,
memberId: pairUnlockEntry.memberId,
resourceId,
});
pairLockEntry = null;
pairUnlockEntry = entry;
}
break;
case doorLockEvents.USER_LOCKED:
if (pairUnlockEntry && !pairLockEntry){
pairLockEntry = entry;
const emptyReservation = {
reservationId: null,
start: null,
end: null,
};
const unlockMoment = moment.utc(pairUnlockEntry.timestamp);
const lockMoment = moment.utc(pairLockEntry.timestamp);
if (lockMoment.tz(UI_TIMEZONE).isSame(unlockMoment.tz(UI_TIMEZONE), 'day')){
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({ incidents.push({
incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE, incidentType: incidentType.UNSCHEDULED_INCIDENT_STANDALONE,
reservation: emptyReservation, reservation: emptyReservation,
unlockTimestamp: pairUnlockEntry.timestamp, unlockTimestamp: pairUnlockEntry.timestamp,
lockTimestamp: pairLockEntry.timestamp,
memberId: pairUnlockEntry.memberId, memberId: pairUnlockEntry.memberId,
resourceId, resourceId,
chargePrice: UNSCHEDULED_CHARGE_PRICE,
timeIntervalsToCharge,
totalChargeFee,
}); });
pairLockEntry = null;
pairUnlockEntry = entry;
} }
break; }else{
case doorLockEvents.USER_LOCKED: const emptyReservation = {
if (pairUnlockEntry && !pairLockEntry){ reservationId: null,
pairLockEntry = entry; start: null,
const emptyReservation = { end: null,
reservationId: null, };
start: null,
end: null,
};
const unlockMoment = moment.utc(pairUnlockEntry.timestamp);
const lockMoment = moment.utc(pairLockEntry.timestamp);
if (lockMoment.tz(UI_TIMEZONE).isSame(unlockMoment.tz(UI_TIMEZONE), 'day')){ incidents.push({
const timeDifference = lockMoment.diff(unlockMoment, 'minutes'); incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE,
const timeIntervalsToCharge = Math.floor(timeDifference / UNSCHEDULED_TIME_RESOLUTION); reservation: emptyReservation,
const totalChargeFee = timeIntervalsToCharge * UNSCHEDULED_CHARGE_PRICE; unlockTimestamp: pairUnlockEntry.timestamp,
if (timeIntervalsToCharge > 0){ memberId: pairUnlockEntry.memberId,
incidents.push({ resourceId,
incidentType: incidentType.UNSCHEDULED_INCIDENT_STANDALONE, });
reservation: emptyReservation, }
unlockTimestamp: pairUnlockEntry.timestamp,
lockTimestamp: pairLockEntry.timestamp,
memberId: pairUnlockEntry.memberId,
resourceId,
chargePrice: UNSCHEDULED_CHARGE_PRICE,
timeIntervalsToCharge,
totalChargeFee,
});
}
}else{
const emptyReservation = {
reservationId: null,
start: null,
end: null,
};
incidents.push({ pairUnlockEntry = null;
incidentType: incidentType.UNLOCKED_INCIDENT_STANDALONE, pairLockEntry = null;
reservation: emptyReservation, }else{
unlockTimestamp: pairUnlockEntry.timestamp, if (!pairUnlockEntry){
memberId: pairUnlockEntry.memberId, pairLockEntry = entry;
resourceId, //Only lock entry, ignore now
}); }
} pairLockEntry = null;
pairUnlockEntry = null;
pairUnlockEntry = null;
pairLockEntry = null;
}else{
if (!pairUnlockEntry){
pairLockEntry = entry;
//Only lock entry, ignore now
}
pairLockEntry = null;
pairUnlockEntry = null;
}
} }
} }
}); }
});
//Now wait also for "forgotToLockAsyncCheck" to finish //Now wait also for "forgotToLockAsyncCheck" to finish

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 : [];
bookingData.forEach((fullBookingEntry) => { const bookingsToCreate = [];
const fees = fullBookingEntry && fullBookingEntry.fees ? fullBookingEntry.fees : []; const bookingIdsToRemove = [];
const firstFee = fees.length > 0 && fees[0].fee ? fees[0].fee : undefined;
const hourlyRate = firstFee && firstFee.price ? firstFee.price : 0;
cleanedBookingReservations.push({ bookingData.forEach(fullBookingEntry => {
reservationId: fullBookingEntry['_id'], if (!fullBookingEntry){
memberId: fullBookingEntry.member, return;
officeId: fullBookingEntry.office, }
resourceId: fullBookingEntry.resourceId, const fees = fullBookingEntry.fees ? fullBookingEntry.fees : [];
start: fullBookingEntry.start.dateTime,
end: fullBookingEntry.end.dateTime, if (fees.length > 1){
timezone: fullBookingEntry.timezone, // Recurring booking, let's create new booking
canceled: fullBookingEntry.canceled || false, const member = fullBookingEntry.member ? fullBookingEntry.member : null;
hourlyRate, 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']);
}
}); });
resolve(cleanedBookingReservations);
//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) => {
const fees = fullBookingEntry && fullBookingEntry.fees ? fullBookingEntry.fees : [];
const firstFee = fees.length > 0 && fees[0].fee ? fees[0].fee : undefined;
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({
reservationId: fullBookingEntry['_id'],
memberId: fullBookingEntry.member,
officeId: fullBookingEntry.office,
resourceId: fullBookingEntry.resourceId,
start: startMoment.toISOString(),
end: endMoment.toISOString(),
timezone: fullBookingEntry.timezone,
canceled: fullBookingEntry.canceled || false,
hourlyRate,
});
}
});
resolve(cleanedBookingReservations);
}
}) })
.catch((error) => { .catch((error) => {
console.log(officeRnDAPIErrors.FAILED_TO_FETCH_BOOKINGS); console.log(officeRnDAPIErrors.FAILED_TO_FETCH_BOOKINGS);