Fix for loading

This commit is contained in:
Senad Uka
2019-07-25 06:53:32 +02:00
parent a691ab94c7
commit 2db47e95e1
26 changed files with 838 additions and 400 deletions

View File

@@ -97,7 +97,7 @@ const chargeBookingChanges = (changes) => {
incidents.push(incident);
}
}else{
const differenceFromCreation = reservationCreationTimestamp.diff(moment.utc(), 'minutes');
const differenceFromCreation = moment.utc().diff(reservationCreationTimestamp, 'minutes');
if (differenceFromCreation > ALLOWED_BOOKING_CANCELLATION_TIME){
const chargeFee = 2 * reservationHourlyRate * oldReservationLength * BOOKING_CHANGE_PERCENTAGE_CHARGE / 100;

View File

@@ -0,0 +1,53 @@
'use strict';
const Op = require('sequelize').Op;
const db = require('../../models/index');
const moment = require('moment-timezone');
const { DEFAULT_DATE_FORMAT, UI_TIMEZONE } = require('../../constants/constants');
const getActiveBookingsForMembersInDateRange = (dateRange, memberIds) => {
const startDate = moment.tz(dateRange.startDate, DEFAULT_DATE_FORMAT, UI_TIMEZONE).startOf('day');
const endDate = moment.tz(dateRange.endDate, DEFAULT_DATE_FORMAT, UI_TIMEZONE).endOf('day');
const attributes = [
'id',
'reservationId',
'memberId',
'officeId',
'resourceId',
'start',
'end',
'timezone',
'canceled',
'hourlyRate'
];
const filters = {
canceled: false,
};
if (startDate && endDate) {
filters.start = {
[Op.gte]: startDate.toISOString()
};
filters.end = {
[Op.lte]: endDate.toISOString(),
};
}
if (memberIds.length > 0){
filters.memberId = {
[Op.in]: memberIds
};
}
return db.bookingReservation.findAll({
attributes,
where: filters,
});
};
module.exports = {
getActiveBookingsForMembersInDateRange,
};

View File

@@ -0,0 +1,44 @@
'use strict';
const { fetchAllBookings, bulkWriteReservationsWithChangesTracking } = require('../officeRnD/bookings');
const { chargeBookingChanges } = require('./bookingChangeCharges');
const { bulkWriteChanges } = require('./bookingChangeLog');
const checkBookingChanges = () => {
return new Promise((resolve, reject) => {
fetchAllBookings()
.then((reservations) => {
bulkWriteReservationsWithChangesTracking(reservations)
.then((changes) => {
bulkWriteChanges(changes)
.then(() => {
chargeBookingChanges(changes)
.then(() => {
resolve(true);
})
.catch((error) => {
console.log('Error creating charges ', error);
reject(error);
});
})
.catch((error) => {
console.log('Error bulk write booking reservation change log :', error);
reject(error);
});
})
.catch((error) => {
console.log('Error bulk write booking reservations :', error);
reject(error);
});
})
.catch((error) => {
console.log('Error fetching bookings from ORD ', error);
reject(error);
});
});
};
module.exports = {
checkBookingChanges
};

View File

@@ -510,52 +510,66 @@ const getIncidentData = (reservation) => {
};
const calculateDoorLockCharges = () => {
getAllFinishedBookings()
.then((reservations) => {
const unlockedIncidents = [];
const unscheduledIncidents = [];
return new Promise((resolve, reject) => {
getAllFinishedBookings()
.then((reservations) => {
const unlockedIncidents = [];
const unscheduledIncidents = [];
const asyncCheckForIncidents = [];
const asyncCheckForIncidents = [];
reservations.forEach((reservation) => {
asyncCheckForIncidents.push(getIncidentData(reservation));
});
reservations.forEach((reservation) => {
asyncCheckForIncidents.push(getIncidentData(reservation));
});
Promise.all(asyncCheckForIncidents)
.then((allReservationsIncidents) => {
allReservationsIncidents.forEach((reservationIncidents) => {
reservationIncidents.forEach((incident) => {
if (incident.error) {
console.log('Error checking incident : ', incident.error);
} else if (incident.incidentType) {
switch (incident.incidentType) {
case incidentType.UNLOCKED_INCIDENT_RELATED_WITH_RESERVATION:
case incidentType.UNLOCKED_INCIDENT_STANDALONE:
unlockedIncidents.push(incident);
break;
case incidentType.UNSCHEDULED_INCIDENT_BEFORE_RESERVATION:
case incidentType.UNSCHEDULED_INCIDENT_AFTER_RESERVATION:
case incidentType.UNSCHEDULED_INCIDENT_STANDALONE:
unscheduledIncidents.push(incident);
break;
Promise.all(asyncCheckForIncidents)
.then((allReservationsIncidents) => {
allReservationsIncidents.forEach((reservationIncidents) => {
reservationIncidents.forEach((incident) => {
if (incident.error) {
console.log('Error checking incident : ', incident.error);
} else if (incident.incidentType) {
switch (incident.incidentType) {
case incidentType.UNLOCKED_INCIDENT_RELATED_WITH_RESERVATION:
case incidentType.UNLOCKED_INCIDENT_STANDALONE:
unlockedIncidents.push(incident);
break;
case incidentType.UNSCHEDULED_INCIDENT_BEFORE_RESERVATION:
case incidentType.UNSCHEDULED_INCIDENT_AFTER_RESERVATION:
case incidentType.UNSCHEDULED_INCIDENT_STANDALONE:
unscheduledIncidents.push(incident);
break;
}
}
}
});
});
});
insertUnscheduledIncidents(unscheduledIncidents)
.catch((error) => console.log(error));
setUnlockedIncidentsLevel(unlockedIncidents)
.then((completedUnlockedIncidents) => {
const insertIncidentsJobs = [insertUnscheduledIncidents(unscheduledIncidents), insertUnlockedIncidents(completedUnlockedIncidents)];
setUnlockedIncidentsLevel(unlockedIncidents)
.then((completedUnlockedIncidents) => {
insertUnlockedIncidents(completedUnlockedIncidents)
.catch((error) => console.log(error));
})
.catch((error) => console.log(error));
})
.catch((error) => console.log(error));
})
.catch((error) => console.log(error));
Promise.all(insertIncidentsJobs)
.then(() => {
resolve(true);
})
.catch((error) => {
reject(error);
});
/*
insertUnscheduledIncidents(unscheduledIncidents)
.catch((error) => console.log(error));
insertUnlockedIncidents(completedUnlockedIncidents)
.catch((error) => console.log(error));
*/
})
.catch((error) => reject(error));
})
.catch((error) => reject(error));
})
.catch((error) => reject(error));
});
};
module.exports = {

View File

@@ -0,0 +1,257 @@
'use strict';
const moment = require('moment-timezone');
const { getAllIncidents } = require('./reports');
const { getActiveBookingsForMembersInDateRange } = require('./bookings');
const { DEFAULT_DATE_FORMAT, UI_TIMEZONE, incidentTypeExplanations, incidentType, unlockedIncidentLevelsPrices } = require('../../constants/constants');
const { getResourceMappings } = require('../officeRnD/resources');
const { fetchAllMembers } = require('../officeRnD/members');
const createFeeFromIncident = (incident) => {
const {
memberId,
officeId,
officeName,
resourceName,
oldResourceName,
newResourceName,
bookingStartRaw,
bookingEndRaw,
oldBookingStartRaw,
oldBookingEndRaw,
newBookingStartRaw,
newBookingEndRaw,
unlockTimestampRaw,
lockTimestampRaw,
incidentLevel,
timeIntervalsToCharge,
incidentPrice,
chargePrice,
totalChargeFee,
incidentTimestampRaw
} = incident;
const incidentTypeNumber = incident.incidentType;
const incidentExplanation = incidentTypeExplanations[incidentTypeNumber];
let date = '';
let price = 0;
let quantity = 0;
let priceExplanation = '';
let bookingTimeExplanation = '';
let incidentTimeExplanation = '';
let additionalIncidentExplanation = '';
let roomExplanation = '';
let dateExplanation = '';
const bookingStartMoment = moment.tz(bookingStartRaw, UI_TIMEZONE);
const bookingEndMoment = moment.tz(bookingEndRaw, UI_TIMEZONE);
const unlockMoment = moment.tz(unlockTimestampRaw, UI_TIMEZONE);
const lockMoment = moment.tz(lockTimestampRaw, UI_TIMEZONE);
const oldBookingStartMoment = moment.tz(oldBookingStartRaw, UI_TIMEZONE);
const oldBookingEndMoment = moment.tz(oldBookingEndRaw, UI_TIMEZONE);
const newBookingStartMoment = moment.tz(newBookingStartRaw, UI_TIMEZONE);
const newBookingEndMoment = moment.tz(newBookingEndRaw, UI_TIMEZONE);
const incidentTimestampMoment = moment.tz(incidentTimestampRaw, UI_TIMEZONE);
switch (incidentTypeNumber){
case incidentType.UNLOCKED_INCIDENT_RELATED_WITH_RESERVATION:
roomExplanation = resourceName;
dateExplanation = bookingStartMoment.clone().startOf('day').format('MMM DD, YYYY');
bookingTimeExplanation = `${bookingStartMoment.clone().format('HH:mm a')} - ${bookingEndMoment.clone().format('HH:mm a')}`;
incidentTimeExplanation = `UNLOCK : ${unlockMoment.clone().format('HH:mm a')}`;
unlockedIncidentLevelsPrices[incidentLevel].description
additionalIncidentExplanation = unlockedIncidentLevelsPrices[incidentLevel].description;
date = bookingStartMoment.clone().startOf('day').format();
price = incidentPrice;
quantity = 1;
priceExplanation = `$${price.toFixed(2)}, 1 x $${price.toFixed(2)}`;
break;
case incidentType.UNSCHEDULED_INCIDENT_BEFORE_RESERVATION:
roomExplanation = resourceName;
dateExplanation = bookingStartMoment.clone().startOf('day').format('MMM DD, YYYY');
bookingTimeExplanation = `${bookingStartMoment.clone().format('HH:mm a')} - ${bookingEndMoment.clone().format('HH:mm a')}`;
incidentTimeExplanation = `UNLOCK : ${unlockMoment.clone().format('HH:mm a')}`;
date = bookingStartMoment.clone().startOf('day').format();
price = chargePrice;
quantity = timeIntervalsToCharge;
priceExplanation = `$${totalChargeFee.toFixed(2)}, ${quantity} x $${price.toFixed(2)}`;
break;
case incidentType.UNSCHEDULED_INCIDENT_AFTER_RESERVATION:
roomExplanation = resourceName;
dateExplanation = bookingStartMoment.clone().startOf('day').format('MMM DD, YYYY');
bookingTimeExplanation = `${bookingStartMoment.clone().format('HH:mm a')} - ${bookingEndMoment.clone().format('HH:mm a')}`;
incidentTimeExplanation = `LOCK : ${lockMoment.clone().format('HH:mm a')}`;
date = bookingStartMoment.clone().startOf('day').format();
price = chargePrice;
quantity = timeIntervalsToCharge;
priceExplanation = `$${totalChargeFee.toFixed(2)}, ${quantity} x $${price.toFixed(2)}`;
break;
case incidentType.UNLOCKED_INCIDENT_STANDALONE:
roomExplanation = resourceName;
dateExplanation = unlockMoment.clone().startOf('day').format('MMM DD, YYYY');
bookingTimeExplanation = `NO RESERVATION`;
incidentTimeExplanation = `UNLOCK : ${unlockMoment.clone().format('HH:mm a')}`;
additionalIncidentExplanation = unlockedIncidentLevelsPrices[incidentLevel].description;
date = unlockMoment.clone().startOf('day').format();
price = incidentPrice;
quantity = 1;
priceExplanation = `$${price.toFixed(2)}, 1 x $${price.toFixed(2)}`;
break;
case incidentType.UNSCHEDULED_INCIDENT_STANDALONE:
roomExplanation = resourceName;
dateExplanation = unlockMoment.clone().startOf('day').format('MMM DD, YYYY');
bookingTimeExplanation = `NO RESERVATION`;
incidentTimeExplanation = `UNLOCK : ${unlockMoment.clone().format('HH:mm a')} LOCK : ${lockMoment.clone().format('HH:mm a')}`;
additionalIncidentExplanation = '';
date = unlockMoment.clone().startOf('day').format();
price = chargePrice;
quantity = timeIntervalsToCharge;
priceExplanation = `$${totalChargeFee.toFixed(2)}, ${quantity} x $${price.toFixed(2)}`;
break;
case incidentType.BOOKING_MOVED_TO_ANOTHER_DAY:
if (oldResourceName !== newResourceName){
roomExplanation = `${oldResourceName} -> ${newResourceName}`;
}else{
roomExplanation = oldResourceName;
}
dateExplanation = `${oldBookingStartMoment.clone().format('MMM DD, YYYY')} -> ${newBookingStartMoment.clone().format('MMM DD, YYYY')}`;
bookingTimeExplanation = `(${oldBookingStartMoment.clone().format('HH:mm a')} - ${oldBookingEndMoment.clone().format('HH:mm a')}) -> (${newBookingStartMoment.clone().format('HH:mm a')} - ${newBookingEndMoment.clone().format('HH:mm a')})`;
incidentTimeExplanation = `MOVED ON : ${incidentTimestampMoment.clone().format('MMM DD, YYYY')}`;
date = incidentTimestampMoment.clone().startOf('day').format();
price = totalChargeFee;
quantity = 1;
priceExplanation = `$${totalChargeFee.toFixed(2)}, 1 x $${price.toFixed(2)}`;
break;
case incidentType.BOOKING_SHORTENED:
if (oldResourceName !== newResourceName){
roomExplanation = `${oldResourceName} -> ${newResourceName}`;
}else{
roomExplanation = oldResourceName;
}
dateExplanation = `${oldBookingStartMoment.clone().format('MMM DD, YYYY')}`;
bookingTimeExplanation = `(${oldBookingStartMoment.clone().format('HH:mm a')} - ${oldBookingEndMoment.clone().format('HH:mm a')}) -> (${newBookingStartMoment.clone().format('HH:mm a')} - ${newBookingEndMoment.clone().format('HH:mm a')})`;
incidentTimeExplanation = `SHORTENED ON : ${incidentTimestampMoment.clone().format('MMM DD, YYYY')}`;
date = incidentTimestampMoment.clone().startOf('day').format();
price = totalChargeFee;
quantity = 1;
priceExplanation = `$${totalChargeFee.toFixed(2)}, 1 x $${price.toFixed(2)}`;
break;
case incidentType.BOOKING_CANCELED_LATE:
roomExplanation = oldResourceName;
dateExplanation = `${oldBookingStartMoment.clone().format('MMM DD, YYYY')}`;
bookingTimeExplanation = `${oldBookingStartMoment.clone().format('HH:mm a')} - ${oldBookingEndMoment.clone().format('HH:mm a')}`;
incidentTimeExplanation = `CANCELED ON : ${incidentTimestampMoment.clone().format('MMM DD, YYYY')}`;
date = incidentTimestampMoment.clone().startOf('day').format();
price = totalChargeFee;
quantity = 1;
priceExplanation = `$${totalChargeFee.toFixed(2)}, 1 x $${price.toFixed(2)}`;
break;
}
const formattedName = `[INCIDENT FEES] ${officeName}, ${roomExplanation}, ${dateExplanation}, ${bookingTimeExplanation}, ${incidentTimeExplanation}, ${incidentExplanation}, ${additionalIncidentExplanation} ${additionalIncidentExplanation !== '' ? ',' : ''} ${priceExplanation}`;
return {
name: formattedName,
price,
quantity,
date,
member: memberId,
team: null,
office: officeId,
isPersonal: false,
}
};
const createFeeFromBooking = (booking, resourceMappings) => {
const { officeId, resourceId, memberId, start, end, timezone, hourlyRate } = booking;
const { officesMap, resourcesMap } = resourceMappings;
const startMoment = moment.tz(start, DEFAULT_DATE_FORMAT, timezone);
const endMoment = moment.tz(end, DEFAULT_DATE_FORMAT, timezone);
const reservationLength = endMoment.diff(startMoment, 'hours', true);
const officeName = officesMap[officeId].officeName || 'Unknown';
const resourceName = resourcesMap[resourceId].resourceName || 'Unknown';
const totalCost = (hourlyRate*reservationLength).toFixed(2);
const formattedDate = startMoment.clone().startOf('day').format('MMM DD, YYYY');
const formattedStartTime = startMoment.format('HH:mm a');
const formattedEndTime = endMoment.format('HH:mm a');
const formattedName = `[BOOKING FEES] ${officeName}, ${resourceName}, $${totalCost}, ${reservationLength.toFixed(2)} x $${hourlyRate.toFixed(2)}, ${formattedDate} [${formattedStartTime} - ${formattedEndTime}]`;
return {
name: formattedName,
price: hourlyRate,
quantity: reservationLength,
date: startMoment.startOf('day').toISOString(),
member: memberId,
team: null,
office: officeId,
isPersonal: false,
}
};
const getMembersFeesForDateRange = (dateRange, memberIds) => {
return new Promise((resolve, reject) => {
const collectData = [getAllIncidents(dateRange, memberIds), getActiveBookingsForMembersInDateRange(dateRange, memberIds), getResourceMappings(), fetchAllMembers()];
Promise.all(collectData)
.then((result) => {
const allIncidents = result[0];
const allActiveBookings = result[1];
const resourceMappings = result[2];
const membersList = result[3];
const memberIdTeamMappings = {};
membersList.forEach((member) => {
memberIdTeamMappings[member.memberId] = member.teamId;
});
const allFees = [];
allIncidents.forEach((incident) => allFees.push(createFeeFromIncident(incident)));
allActiveBookings.forEach((booking) => allFees.push(createFeeFromBooking(booking, resourceMappings)));
allFees.forEach((fee) => {
fee.team = memberIdTeamMappings[fee.member] || null;
});
resolve(allFees);
})
.catch((error) => {
console.log(error);
reject(error);
});
});
};
module.exports = {
getMembersFeesForDateRange,
};

View File

@@ -10,7 +10,7 @@ const { incidentType, UI_TIMEZONE, DEFAULT_DATE_FORMAT, integrationServiceErrors
const { fetchAllMembers } = require('../officeRnD/members');
const { fetchOffices, fetchResources } = require('../officeRnD/resources');
const getUnlockedIncidents = (startDate, endDate, memberId) => {
const getUnlockedIncidents = (startDate, endDate, memberIds) => {
const attributes = ['id', 'reservationId', 'memberId', 'resourceId', 'bookingStart', 'bookingEnd', 'unlockTimestamp', 'incidentLevel', 'incidentLevelPrice'];
const filters = {};
@@ -41,8 +41,10 @@ const getUnlockedIncidents = (startDate, endDate, memberId) => {
Object.assign(filters, bookingStartOrUnlockTimestamp);
}
if (memberId){
filters.memberId = memberId;
if (memberIds.length > 0){
filters.memberId = {
[Op.in]: memberIds
};
}
return db.unlockedIncident.findAll({
@@ -54,7 +56,7 @@ const getUnlockedIncidents = (startDate, endDate, memberId) => {
});
};
const getUnscheduledIncidents = (startDate, endDate, memberId) => {
const getUnscheduledIncidents = (startDate, endDate, memberIds) => {
const attributes = [
'id',
'reservationId',
@@ -98,8 +100,10 @@ const getUnscheduledIncidents = (startDate, endDate, memberId) => {
}
if (memberId){
filters.memberId = memberId;
if (memberIds.length > 0){
filters.memberId = {
[Op.in]: memberIds
};
}
return db.unscheduledIncident.findAll({
@@ -111,7 +115,7 @@ const getUnscheduledIncidents = (startDate, endDate, memberId) => {
});
};
const getBookingChangeIncidents = (startDate, endDate, memberId) => {
const getBookingChangeIncidents = (startDate, endDate, memberIds) => {
const attributes = [
'id',
'reservationId',
@@ -138,8 +142,10 @@ const getBookingChangeIncidents = (startDate, endDate, memberId) => {
}
}
if (memberId){
filters.memberId = memberId;
if (memberIds.length > 0){
filters.memberId = {
[Op.in]: memberIds
};
}
return db.bookingChangeIncident.findAll({
@@ -160,7 +166,7 @@ const formatTime = (timestamp) => {
}
};
const getAllIncidents = (dateRange, memberId) => {
const getAllIncidents = (dateRange, memberIds) => {
return new Promise ((resolve, reject) => {
let startDate, endDate;
@@ -178,9 +184,9 @@ const getAllIncidents = (dateRange, memberId) => {
fetchAllMembers(),
fetchOffices(),
fetchResources(),
getUnlockedIncidents(startDate, endDate, memberId),
getUnscheduledIncidents(startDate, endDate, memberId),
getBookingChangeIncidents(startDate, endDate, memberId)
getUnlockedIncidents(startDate, endDate, memberIds),
getUnscheduledIncidents(startDate, endDate, memberIds),
getBookingChangeIncidents(startDate, endDate, memberIds)
];
Promise.all(dataFetchJobs)
@@ -210,10 +216,14 @@ const getAllIncidents = (dateRange, memberId) => {
memberId: unlockedIncident.memberId,
memberName: membersMap[unlockedIncident.memberId].name,
resourceName: resourcesMap[unlockedIncident.resourceId].resourceName,
officeId: resourcesMap[unlockedIncident.resourceId].officeId,
officeName: officesMap[resourcesMap[unlockedIncident.resourceId].officeId].officeName,
bookingStart: formatTime(unlockedIncident.bookingStart),
bookingEnd: formatTime(unlockedIncident.bookingEnd),
bookingStartRaw: unlockedIncident.bookingStart,
bookingEndRaw: unlockedIncident.bookingEnd,
unlockTimestamp: formatTime(unlockedIncident.unlockTimestamp),
unlockTimestampRaw: unlockedIncident.unlockTimestamp,
incidentType: incidentTypeNumber,
incidentLevel: unlockedIncident.incidentLevel,
incidentPrice: unlockedIncident.incidentLevelPrice,
@@ -236,11 +246,16 @@ const getAllIncidents = (dateRange, memberId) => {
memberId: unscheduledIncident.memberId,
memberName: membersMap[unscheduledIncident.memberId].name,
resourceName: resourcesMap[unscheduledIncident.resourceId].resourceName,
officeId: resourcesMap[unscheduledIncident.resourceId].officeId,
officeName: officesMap[resourcesMap[unscheduledIncident.resourceId].officeId].officeName,
bookingStart: formatTime(unscheduledIncident.bookingStart),
bookingEnd: formatTime(unscheduledIncident.bookingEnd),
bookingStartRaw: unscheduledIncident.bookingStart,
bookingEndRaw: unscheduledIncident.bookingEnd,
unlockTimestamp: formatTime(unscheduledIncident.unlockTimestamp),
lockTimestamp: formatTime(unscheduledIncident.lockTimestamp),
unlockTimestampRaw: unscheduledIncident.unlockTimestamp,
lockTimestampRaw: unscheduledIncident.lockTimestamp,
incidentType: incidentTypeNumber,
timeIntervalsToCharge: unscheduledIncident.timeIntervalsToCharge,
chargePrice: unscheduledIncident.chargePrice,
@@ -267,21 +282,28 @@ const getAllIncidents = (dateRange, memberId) => {
const newResource = newResourceId ? resourcesMap[newResourceId] : null;
const oldResourceName = oldResource.resourceName;
const newResourceName = newResource ? newResource.resourceName : null;
const officeName = officesMap[oldResource.officeId].officeName;
const officeId = oldResource.officeId;
const officeName = officesMap[officeId].officeName;
allIncidents.push({
incidentId: id,
memberId,
memberName,
oldResourceName,
newResourceName,
officeId,
officeName,
oldBookingStart: formatTime(oldBookingStart),
oldBookingEnd: formatTime(oldBookingEnd),
newBookingStart: formatTime(newBookingStart),
newBookingEnd: formatTime(newBookingEnd),
oldBookingStartRaw: oldBookingStart,
oldBookingEndRaw: oldBookingEnd,
newBookingStartRaw: newBookingStart,
newBookingEndRaw: newBookingEnd,
incidentType,
totalChargeFee: chargeFee,
incidentTimestamp: formatTime(createdAt),
incidentTimestampRaw: createdAt,
});
});
@@ -292,7 +314,5 @@ const getAllIncidents = (dateRange, memberId) => {
};
module.exports = {
getUnlockedIncidents,
getUnscheduledIncidents,
getAllIncidents,
};