diff --git a/client/package.json b/client/package.json
index c87178e..16941b2 100644
--- a/client/package.json
+++ b/client/package.json
@@ -4,6 +4,7 @@
"private": true,
"dependencies": {
"axios": "^0.18.0",
+ "fuse.js": "^3.4.5",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^7.0.3",
diff --git a/client/src/scenes/UploadDLockData/components/FileUpload.js b/client/src/scenes/UploadDLockData/components/FileUpload.js
index b185805..87b1038 100644
--- a/client/src/scenes/UploadDLockData/components/FileUpload.js
+++ b/client/src/scenes/UploadDLockData/components/FileUpload.js
@@ -1,37 +1,96 @@
import React, { Component } from 'react';
import { connect } from 'react-redux';
-import {Form} from "semantic-ui-react";
+import { Form } from "semantic-ui-react";
-import { uploadDoorLockData } from "../../../store/actions";
+import UnknownMapping from './UnknownMapping';
+
+import { uploadDoorLockData, fetchMappings } from "../../../store/actions";
class FileUpload extends Component {
constructor(props) {
super(props);
this.state = {
- file: null,
+ files: null,
+ unknownMappings: [],
};
this.onFileChange = this.onFileChange.bind(this);
this.onUploadClick = this.onUploadClick.bind(this);
}
+ componentDidMount() {
+ const { fetchMappings } = this.props;
+ fetchMappings();
+ }
+
+ componentWillReceiveProps(nextProps, nextContext) {
+ const { addedMapping } = nextProps;
+ const { unknownMappings } = this.state;
+
+ const filteredUnknownMappings = unknownMappings.filter(mapping => {
+ return mapping.officeSlug !== addedMapping.officeSlug
+ || mapping.resourceSlug !== addedMapping.resourceSlug
+ });
+
+ this.setState({unknownMappings: filteredUnknownMappings});
+ }
+
+ extractMappingFromFileName(fileName) {
+ const contentBetweenBracketsRegex = /\[(.*?)\]/;
+ const rawContent = fileName.match(contentBetweenBracketsRegex)[1];
+ const mappingContent = rawContent.split('-').map(word => word.trim());
+ return {
+ officeSlug: mappingContent[0],
+ resourceSlug: mappingContent[1],
+ }
+ }
+
+ checkIfMappingExsists(mappingFromFileName) {
+ const { mappings } = this.props;
+ const { officeSlug, resourceSlug } = mappingFromFileName;
+
+ const { existingMappings } = mappings;
+
+ return existingMappings.find(mapping => (mapping.officeSlug === officeSlug) && (mapping.resourceSlug === resourceSlug));
+ }
+
onFileChange(event) {
- const file = event.target.files[0];
- this.setState({file});
+ const files = event.target.files;
+ const unknownMappings = [];
+
+
+ Array.from(files).forEach(file => {
+ const mappingFromFileName = this.extractMappingFromFileName(file.name);
+ if (!this.checkIfMappingExsists(mappingFromFileName)){
+ unknownMappings.push({
+ file: file.name,
+ officeId: null,
+ resourceId: null,
+ officeSlug: mappingFromFileName.officeSlug,
+ resourceSlug: mappingFromFileName.resourceSlug,
+ })
+ }
+ });
+
+ this.setState({files, unknownMappings});
};
onUploadClick() {
const { uploadDoorLockData } = this.props;
- const { file } = this.state;
+ const { files } = this.state;
- if (file) {
- uploadDoorLockData(file);
+ if (files) {
+ uploadDoorLockData(files);
}
};
render() {
- const { pending } = this.props;
+ const { pendingUpload } = this.props;
+ const { unknownMappings, files } = this.state;
+
+ const uploadDisabled = pendingUpload || unknownMappings.length > 0 || !files;
+
return (
- Upload
+ {
+ unknownMappings.map((mapping, index) =>
+ )
+ }
+
+ Upload
);
}
}
const mapStateToProps = (state) => ({
- pending: state.doorLockData.pending,
+ pendingUpload: state.doorLockData.pending,
+ pendingMappings: state.mappingsData.pending,
+ mappings: state.mappingsData.result,
+ addedMapping: state.addMapping.result,
});
const mapDispatchToProps = (dispatch) => ({
- uploadDoorLockData: (doorLockDataFile) => uploadDoorLockData(dispatch, doorLockDataFile)
+ uploadDoorLockData: (doorLockDataFiles) => uploadDoorLockData(dispatch, doorLockDataFiles),
+ fetchMappings: () => fetchMappings(dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(FileUpload);
diff --git a/client/src/scenes/UploadDLockData/components/UnknownMapping.js b/client/src/scenes/UploadDLockData/components/UnknownMapping.js
new file mode 100644
index 0000000..3bee93e
--- /dev/null
+++ b/client/src/scenes/UploadDLockData/components/UnknownMapping.js
@@ -0,0 +1,172 @@
+import React, { Component } from 'react';
+import { connect } from 'react-redux';
+import {Button, Dropdown, Message} from "semantic-ui-react";
+import Fuse from 'fuse.js';
+import { addNewMapping } from "../../../store/actions";
+
+class UnknownMapping extends Component {
+ constructor(props) {
+ super(props);
+
+ const guessedValues = this.guessDropdownValues(this.props);
+
+ this.state = {
+ selectedOfficeId: guessedValues.officeValue,
+ selectedResourceId: guessedValues.resourceValue,
+ }
+ }
+
+ componentWillReceiveProps(nextProps, nextContext) {
+ const guessedValues = this.guessDropdownValues(nextProps);
+ this.setState({selectedOfficeId: guessedValues.officeValue, selectedResourceId: guessedValues.resourceValue});
+ }
+
+ guessDropdownValues(props){
+ const { mappings, mapping } = props;
+
+ const offices = mappings && mappings.offices ? mappings.offices : [];
+ const resources = mappings && mappings.resources ? mappings.resources : [];
+
+ const fuzzySearchOptions = {
+ shouldSort: true,
+ threshold: 0.5,
+ location: 0,
+ distance: 100,
+ maxPatternLength: 32,
+ minMatchCharLength: 1,
+ keys: [
+ "officeName",
+ "resourceName",
+ ]
+ };
+
+ const officesFuse = new Fuse(offices, fuzzySearchOptions);
+ const fuzzyOfficeSearchResults = officesFuse.search(mapping.officeSlug);
+
+ let officeValue = null;
+ if (fuzzyOfficeSearchResults.length > 0){
+ officeValue = fuzzyOfficeSearchResults[0].officeId;
+ }else if (offices.length > 0){
+ officeValue = offices[0].officeId;
+ }
+
+ const filteredResources = resources.filter(resource => resource.officeId === officeValue);
+
+ const resourcesFuse = new Fuse(filteredResources, fuzzySearchOptions);
+ const fuzzyResourcesSearchResults = resourcesFuse.search(mapping.resourceSlug);
+
+ let resourceValue = null;
+ if (fuzzyResourcesSearchResults.length > 0){
+ resourceValue = fuzzyResourcesSearchResults[0].resourceId;
+ }else if (filteredResources.length > 0){
+ resourceValue = filteredResources[0].resourceId;
+ }
+
+ return {
+ officeValue,
+ resourceValue,
+ }
+ }
+
+ onOfficeChange(event, data) {
+ const { mappings } = this.props;
+
+ const selectedOfficeId = data.value || null;
+ const resources = mappings && mappings.resources ? mappings.resources : [];
+ const filteredResources = resources.filter(resource => resource.officeId === selectedOfficeId);
+ const selectedResourceId = filteredResources.length > 0 ? filteredResources[0].resourceId : null;
+ this.setState({selectedOfficeId, selectedResourceId});
+ }
+
+ onResourceChange(event, data) {
+ const selectedResourceId = data.value || null;
+ this.setState({selectedResourceId});
+ }
+
+ onSave(){
+ const { addNewMapping, mapping } = this.props;
+ const { selectedOfficeId, selectedResourceId } = this.state;
+ const officeSlug = mapping.officeSlug;
+ const resourceSlug = mapping.resourceSlug;
+
+ const newMapping = {
+ officeSlug,
+ resourceSlug,
+ officeId: selectedOfficeId,
+ resourceId: selectedResourceId,
+ };
+
+ addNewMapping(newMapping);
+ }
+
+ render() {
+ const { mapping, mappings } = this.props;
+ const { selectedOfficeId, selectedResourceId } = this.state;
+
+ const offices = mappings && mappings.offices ? mappings.offices : [];
+ const resources = mappings && mappings.resources ? mappings.resources : [];
+
+ const officeDropdownOptions = offices.map(office => {
+ return {
+ key: office.officeId,
+ value: office.officeId,
+ text: office.officeName,
+ }
+ });
+
+ const filteredResources = resources.filter(resource => resource.officeId === selectedOfficeId);
+
+ const resourceDropdownOptions = filteredResources.map(resource => {
+ return {
+ key: resource.resourceId,
+ value: resource.resourceId,
+ text: resource.resourceName,
+ }
+ });
+
+ const saveButtonDisabled = !selectedOfficeId || !selectedResourceId;
+
+ return (
+
+
+
+ {mapping.file}
+
+
+ This file contains the unknown location. Based on ORD data, it seems that this file is related to {' '}
+
+ {' '}
+ /
+ {' '}
+
+
+
+ Save
+
+
);
+ }
+}
+
+const mapStateToProps = (state) => ({
+ mappings: state.mappingsData.result,
+});
+
+const mapDispatchToProps = (dispatch) => ({
+ addNewMapping: (mapping) => addNewMapping(dispatch, mapping),
+});
+
+
+export default connect(mapStateToProps, mapDispatchToProps)(UnknownMapping);
diff --git a/client/src/store/actions/doorLockActions.js b/client/src/store/actions/doorLockActions.js
index 00273f4..a5c5a01 100644
--- a/client/src/store/actions/doorLockActions.js
+++ b/client/src/store/actions/doorLockActions.js
@@ -6,9 +6,12 @@ import {
import API from '../../utilities/api';
-export const uploadDoorLockData = (dispatch, doorLockDataFile) => {
+export const uploadDoorLockData = (dispatch, doorLockDataFiles) => {
const formData = new FormData();
- formData.append('doorLockDataFile', doorLockDataFile);
+ const filesArray = Array.from(doorLockDataFiles) || [];
+ filesArray.forEach((file, index) => {
+ formData.append(`doorLockDataFile-${index}`, file);
+ });
const additionalConfig = {
headers: {'content-type': 'multipart/form-data'}
};
diff --git a/client/src/store/actions/index.js b/client/src/store/actions/index.js
index d21e20e..4415670 100644
--- a/client/src/store/actions/index.js
+++ b/client/src/store/actions/index.js
@@ -1 +1,2 @@
export * from './doorLockActions';
+export * from './officeRnDActions';
diff --git a/client/src/store/actions/officeRnDActions.js b/client/src/store/actions/officeRnDActions.js
new file mode 100644
index 0000000..f858967
--- /dev/null
+++ b/client/src/store/actions/officeRnDActions.js
@@ -0,0 +1,34 @@
+import {
+ FETCH_MAPPINGS_PENDING,
+ FETCH_MAPPINGS_SUCCESS,
+ FETCH_MAPPINGS_FAILED,
+ ADD_NEW_MAPPING_PENDING,
+ ADD_NEW_MAPPING_SUCCESS,
+ ADD_NEW_MAPPING_FAILED,
+} from "../constants";
+
+import API from '../../utilities/api';
+
+export const fetchMappings = (dispatch) => {
+ dispatch({type: FETCH_MAPPINGS_PENDING});
+ API.get('doorLock/mappings')
+ .then(response => {
+ dispatch({type: FETCH_MAPPINGS_SUCCESS, payload: response.data});
+ })
+ .catch(error => {
+ dispatch({type: FETCH_MAPPINGS_FAILED, payload: error.response});
+ });
+};
+
+export const addNewMapping = (dispatch, mapping) => {
+ dispatch({type: ADD_NEW_MAPPING_PENDING});
+ API.post('doorLock/mappings', {
+ mapping
+ })
+ .then(response => {
+ dispatch({type: ADD_NEW_MAPPING_SUCCESS, payload: response.data});
+ })
+ .catch(error => {
+ dispatch({type: ADD_NEW_MAPPING_FAILED, payload: error.response});
+ });
+};
diff --git a/client/src/store/constants.js b/client/src/store/constants.js
index 5034375..aecc675 100644
--- a/client/src/store/constants.js
+++ b/client/src/store/constants.js
@@ -1,3 +1,11 @@
export const UPLOAD_DOOR_LOCK_DATA_PENDING = 'UPLOAD_DOOR_LOCK_DATA_PENDING';
export const UPLOAD_DOOR_LOCK_DATA_SUCCESS = 'UPLOAD_DOOR_LOCK_DATA_SUCCESS';
export const UPLOAD_DOOR_LOCK_DATA_FAILED = 'UPLOAD_DOOR_LOCK_DATA_FAILED';
+
+export const FETCH_MAPPINGS_PENDING = 'FETCH_MAPPINGS_PENDING';
+export const FETCH_MAPPINGS_SUCCESS = 'FETCH_MAPPINGS_SUCCESS';
+export const FETCH_MAPPINGS_FAILED = 'FETCH_MAPPINGS_FAILED';
+
+export const ADD_NEW_MAPPING_PENDING = 'ADD_NEW_MAPPING_PENDING';
+export const ADD_NEW_MAPPING_SUCCESS = 'ADD_NEW_MAPPING_SUCCESS';
+export const ADD_NEW_MAPPING_FAILED = 'ADD_NEW_MAPPING_FAILED';
diff --git a/client/src/store/reducers/addMappingReducer.js b/client/src/store/reducers/addMappingReducer.js
new file mode 100644
index 0000000..c360882
--- /dev/null
+++ b/client/src/store/reducers/addMappingReducer.js
@@ -0,0 +1,38 @@
+import {
+ ADD_NEW_MAPPING_PENDING,
+ ADD_NEW_MAPPING_SUCCESS,
+ ADD_NEW_MAPPING_FAILED,
+} from "../constants";
+
+const initialState = {
+ pending: false,
+ result: null,
+ error: null,
+};
+
+export const addMapping = (state, action) => {
+ state = state || initialState;
+ action = action || {};
+
+ switch(action.type){
+ case ADD_NEW_MAPPING_PENDING:
+ return Object.assign({}, state, {
+ pending: true,
+ error: null,
+ });
+ case ADD_NEW_MAPPING_SUCCESS:
+ return Object.assign({}, state, {
+ pending: false,
+ result: action.payload,
+ error: null,
+ });
+ case ADD_NEW_MAPPING_FAILED:
+ return Object.assign({}, state, {
+ pending: false,
+ result: {},
+ error: action.payload,
+ });
+ default:
+ return state;
+ }
+};
diff --git a/client/src/store/reducers/index.js b/client/src/store/reducers/index.js
index 274b7bd..ed2a547 100644
--- a/client/src/store/reducers/index.js
+++ b/client/src/store/reducers/index.js
@@ -1,8 +1,12 @@
import { combineReducers } from "redux";
import { doorLockData} from "./doorLockReducers";
+import { mappingsData } from "./mappingsReducer";
+import { addMapping } from './addMappingReducer';
export const rootReducer = combineReducers({
- doorLockData
+ doorLockData,
+ mappingsData,
+ addMapping,
});
diff --git a/client/src/store/reducers/mappingsReducer.js b/client/src/store/reducers/mappingsReducer.js
new file mode 100644
index 0000000..95e0d9d
--- /dev/null
+++ b/client/src/store/reducers/mappingsReducer.js
@@ -0,0 +1,38 @@
+import {
+ FETCH_MAPPINGS_PENDING,
+ FETCH_MAPPINGS_SUCCESS,
+ FETCH_MAPPINGS_FAILED,
+} from "../constants";
+
+const initialState = {
+ pending: false,
+ result: null,
+ error: null,
+};
+
+export const mappingsData = (state, action) => {
+ state = state || initialState;
+ action = action || {};
+
+ switch(action.type){
+ case FETCH_MAPPINGS_PENDING:
+ return Object.assign({}, state, {
+ pending: true,
+ error: null,
+ });
+ case FETCH_MAPPINGS_SUCCESS:
+ return Object.assign({}, state, {
+ pending: false,
+ result: action.payload,
+ error: null,
+ });
+ case FETCH_MAPPINGS_FAILED:
+ return Object.assign({}, state, {
+ pending: false,
+ result: {},
+ error: action.payload,
+ });
+ default:
+ return state;
+ }
+};
diff --git a/client/yarn.lock b/client/yarn.lock
index 8413b54..a426655 100644
--- a/client/yarn.lock
+++ b/client/yarn.lock
@@ -3680,6 +3680,10 @@ functional-red-black-tree@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327"
+fuse.js@^3.4.5:
+ version "3.4.5"
+ resolved "https://registry.yarnpkg.com/fuse.js/-/fuse.js-3.4.5.tgz#8954fb43f9729bd5dbcb8c08f251db552595a7a6"
+
gauge@~2.7.3:
version "2.7.4"
resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7"
diff --git a/constants/constants.js b/constants/constants.js
index db8cdc9..7344665 100644
--- a/constants/constants.js
+++ b/constants/constants.js
@@ -2,18 +2,22 @@ const USER_ENTRY_EVENT = 'User Entry';
const ENABLE_PASSAGE_MODE = 'Enable Passage Mode by Group 2';
const DISABLE_PASSAGE_MODE = 'Disable Passage Mode by Group 2';
-const USER_LOCKED_DOOR = 'locked';
-const USER_UNLOCKED_DOOR = 'unlocked';
-
const VALID_CSV_HEADERS = ['Date', 'Time', 'User No', 'Name', 'Event'];
+const doorLockEvents = {
+ USER_LOCKED: 'locked',
+ USER_UNLOCKED: 'unlocked',
+};
+const doorChargeTypes = {
+ LEFT_UNLOCKED: 'unlocked',
+ UNSCHEDULED_USE: 'unscheduled'
+};
const csvParserErrors = {
INVALID_HEADERS: 'Invalid headers',
INVALID_ENTRY_EXPECTED_USER: 'Invalid entry type. Expected user entry type',
INVALID_ENTRY_EXPECTED_PASSAGE_MODE: 'Invalid entry type. Expected enable/disable passage mode following user entry',
UNKNOWN_MEMBER: 'Member is not registered in OfficeRnD system',
};
-
const officeRnDAPIErrors = {
FAILED_TO_FETCH_MEMBERS: 'Failed to fetch members',
};
@@ -23,8 +27,8 @@ module.exports = {
USER_ENTRY_EVENT,
ENABLE_PASSAGE_MODE,
DISABLE_PASSAGE_MODE,
- USER_LOCKED_DOOR,
- USER_UNLOCKED_DOOR,
csvParserErrors,
officeRnDAPIErrors,
+ doorLockEvents,
+ doorChargeTypes,
};
diff --git a/controllers/doorLock.js b/controllers/doorLock.js
index 3e57137..7520b3c 100644
--- a/controllers/doorLock.js
+++ b/controllers/doorLock.js
@@ -1,6 +1,7 @@
'use strict';
-const { parseDoorLockDataFile, writeDoorLockEvent } = require("../services/doorLock");
+const { getMappingsFromDatabase, fetchOffices, fetchResources, saveNewMappingToDatabase } = require('../services/officeRnD/resources');
+const { parseDoorLockDataFile, writeDoorLockEvent } = require('../services/doorLock');
const { fetchAllBookings, writeBookingReservation } = require('../services/officeRnD/bookings');
const { officeRnDAPIErrors } = require('../constants/constants');
@@ -8,16 +9,16 @@ const IncomingForm = require('formidable').IncomingForm;
const uploadDoorLockData = (req, res) => {
const form = new IncomingForm();
- const parsingResults = [];
+ const fileParsers = [];
form.on('file', (field, file) => {
if (file && file.type === 'text/csv') {
- parsingResults.push(parseDoorLockDataFile(file));
+ fileParsers.push(parseDoorLockDataFile(file));
}
});
form.on('end', () => {
- Promise.all(parsingResults)
+ Promise.all(fileParsers)
.then((parserResults) => {
const parsedData = [];
const parserErrors = [];
@@ -48,7 +49,7 @@ const uploadDoorLockData = (req, res) => {
writeDoorLockEvent(entry);
});
})
- .catch(() => {
+ .catch((error) => {
res.status(500).send(officeRnDAPIErrors.FAILED_TO_FETCH_MEMBERS);
});
});
@@ -56,6 +57,37 @@ const uploadDoorLockData = (req, res) => {
form.parse(req);
};
+const getKnownOfficeResourceMappings = (req, res) => {
+ const dataToFetch = [getMappingsFromDatabase(), fetchOffices(), fetchResources() ];
+
+ Promise.all(dataToFetch)
+ .then(result => {
+ res.send({
+ existingMappings: result[0],
+ offices: result[1],
+ resources: result[2],
+ });
+ })
+ .catch(error => {
+ res.status(500).send();
+ });
+};
+
+const addNewMapping = (req, res) => {
+ const newMapping = req.body && req.body.mapping ? req.body.mapping : null;
+ if (newMapping && newMapping.officeSlug && newMapping.resourceSlug && newMapping.officeId && newMapping.resourceId){
+ saveNewMappingToDatabase(newMapping)
+ .then(result => {
+ res.send(newMapping);
+ })
+ .catch(error => {
+ res.status(500).send(error);
+ });
+ }
+};
+
module.exports = {
uploadDoorLockData,
+ getKnownOfficeResourceMappings,
+ addNewMapping,
};
diff --git a/migrations/20190603114921-change-resource-column-name-in-tables.js b/migrations/20190603114921-change-resource-column-name-in-tables.js
new file mode 100644
index 0000000..a96138b
--- /dev/null
+++ b/migrations/20190603114921-change-resource-column-name-in-tables.js
@@ -0,0 +1,21 @@
+'use strict';
+
+module.exports = {
+ up: (queryInterface, Sequelize) => {
+ return queryInterface.sequelize.transaction((t) => {
+ return Promise.all([
+ queryInterface.renameColumn('bookingReservations', 'resource', 'resourceId'),
+ queryInterface.renameColumn('doorLockIncidents', 'resource', 'resourceId'),
+ ]);
+ });
+ },
+
+ down: (queryInterface, Sequelize) => {
+ return queryInterface.sequelize.transaction((t) => {
+ return Promise.all([
+ queryInterface.renameColumn('doorLockIncidents', 'resourceId', 'resource'),
+ queryInterface.renameColumn('bookingReservations', 'resourceId', 'resource'),
+ ]);
+ });
+ }
+};
diff --git a/migrations/20190603115116-add-columns-to-booking-reservations-table.js b/migrations/20190603115116-add-columns-to-booking-reservations-table.js
new file mode 100644
index 0000000..04c777c
--- /dev/null
+++ b/migrations/20190603115116-add-columns-to-booking-reservations-table.js
@@ -0,0 +1,27 @@
+'use strict';
+
+module.exports = {
+ up: (queryInterface, Sequelize) => {
+ return queryInterface.sequelize.transaction((t) => {
+ return Promise.all([
+ queryInterface.addColumn('bookingReservations', 'timezone', {
+ type: Sequelize.TEXT,
+ after: 'end'
+ }),
+ queryInterface.addColumn('bookingReservations', 'canceled', {
+ type: Sequelize.BOOLEAN,
+ after: 'timezone'
+ })
+ ]);
+ });
+ },
+
+ down: (queryInterface, Sequelize) => {
+ return queryInterface.sequelize.transaction((t) => {
+ return Promise.all([
+ queryInterface.removeColumn('bookingReservations', 'canceled'),
+ queryInterface.removeColumn('bookingReservations', 'timezone')
+ ]);
+ });
+ }
+};
diff --git a/migrations/20190608093226-create-office-resource-name-mapping.js.js b/migrations/20190608093226-create-office-resource-name-mapping.js.js
new file mode 100644
index 0000000..c158392
--- /dev/null
+++ b/migrations/20190608093226-create-office-resource-name-mapping.js.js
@@ -0,0 +1,41 @@
+'use strict';
+
+module.exports = {
+ up: (queryInterface, Sequelize) => {
+ return queryInterface.createTable('officeResourceMappings', {
+ id: {
+ allowNull: false,
+ autoIncrement: true,
+ primaryKey: true,
+ type: Sequelize.INTEGER
+ },
+ officeSlug: {
+ allowNull: false,
+ type: Sequelize.TEXT,
+ },
+ officeId: {
+ allowNull: false,
+ type: Sequelize.TEXT,
+ },
+ resourceSlug: {
+ allowNull: false,
+ type: Sequelize.TEXT,
+ },
+ resourceId: {
+ allowNull: false,
+ type: Sequelize.TEXT,
+ },
+ createdAt: {
+ allowNull: false,
+ type: Sequelize.DATE
+ },
+ updatedAt: {
+ allowNull: false,
+ type: Sequelize.DATE
+ }
+ });
+ },
+ down: (queryInterface, Sequelize) => {
+ return queryInterface.dropTable('officeResourceMappings');
+ }
+};
diff --git a/migrations/20190608093618-add-resource-column-in-door-lock-events-table.js.js b/migrations/20190608093618-add-resource-column-in-door-lock-events-table.js.js
new file mode 100644
index 0000000..c716163
--- /dev/null
+++ b/migrations/20190608093618-add-resource-column-in-door-lock-events-table.js.js
@@ -0,0 +1,14 @@
+'use strict';
+
+module.exports = {
+ up: (queryInterface, Sequelize) => {
+ return queryInterface.addColumn('doorLockEvents', 'resourceId', {
+ type: Sequelize.TEXT,
+ after: 'memberId',
+ });
+ },
+
+ down: (queryInterface, Sequelize) => {
+ return queryInterface.removeColumn('doorLockEvents', 'resourceId');
+ }
+};
diff --git a/models/bookingReservation.js b/models/bookingReservation.js
index 3a10d3e..9ced517 100644
--- a/models/bookingReservation.js
+++ b/models/bookingReservation.js
@@ -4,9 +4,12 @@ module.exports = (sequelize, DataTypes) => {
const bookingReservation = sequelize.define('bookingReservation', {
reservationId: DataTypes.TEXT,
memberId: DataTypes.TEXT,
- resource: DataTypes.TEXT,
+ resourceId: DataTypes.TEXT,
start: DataTypes.DATE,
end: DataTypes.DATE,
+ timezone: DataTypes.TEXT,
+ canceled: DataTypes.BOOLEAN,
+
}, {});
bookingReservation.associate = function(models) {
// associations can be defined here
diff --git a/models/doorLockEvent.js b/models/doorLockEvent.js
index e0a06e1..5a4a8d8 100644
--- a/models/doorLockEvent.js
+++ b/models/doorLockEvent.js
@@ -1,15 +1,16 @@
'use strict';
-const { USER_LOCKED_DOOR, USER_UNLOCKED_DOOR } = require('../constants/constants');
+const { doorLockEvents } = require('../constants/constants');
module.exports = (sequelize, DataTypes) => {
const doorLockEvent = sequelize.define('doorLockEvent', {
memberName: DataTypes.TEXT,
memberNumber: DataTypes.INTEGER,
memberId: DataTypes.TEXT,
+ resourceId: DataTypes.TEXT,
event: {
type: DataTypes.ENUM,
- values: [USER_LOCKED_DOOR, USER_UNLOCKED_DOOR]
+ values: [doorLockEvents.USER_LOCKED, doorLockEvents.USER_UNLOCKED]
},
timestamp: DataTypes.DATE,
}, {});
diff --git a/models/doorLockIncident.js b/models/doorLockIncident.js
new file mode 100644
index 0000000..4a6e3bb
--- /dev/null
+++ b/models/doorLockIncident.js
@@ -0,0 +1,27 @@
+'use strict';
+
+const { doorLockEvents, doorChargeTypes } = require('../constants/constants');
+
+module.exports = (sequelize, DataTypes) => {
+ const doorLockIncident = sequelize.define('doorLockIncident', {
+ reservationId: DataTypes.TEXT,
+ memberId: DataTypes.TEXT,
+ resourceId: DataTypes.TEXT,
+ bookingStart: DataTypes.DATE,
+ bookingEnd: DataTypes.DATE,
+ doorLockEventTimestamp: DataTypes.DATE,
+ doorLockEventType: {
+ type: DataTypes.ENUM,
+ values: [doorLockEvents.USER_LOCKED, doorLockEvents.USER_UNLOCKED]
+ },
+ chargeType: {
+ type: DataTypes.ENUM,
+ values: [doorChargeTypes.LEFT_UNLOCKED, doorChargeTypes.UNSCHEDULED_USE]
+ },
+ chargeFee: DataTypes.FLOAT,
+ }, {});
+ doorLockIncident.associate = function(models) {
+ // associations can be defined here
+ };
+ return doorLockIncident;
+};
diff --git a/models/officeResourceMapping.js b/models/officeResourceMapping.js
new file mode 100644
index 0000000..7005307
--- /dev/null
+++ b/models/officeResourceMapping.js
@@ -0,0 +1,14 @@
+'use strict';
+
+module.exports = (sequelize, DataTypes) => {
+ const officeResourceMapping = sequelize.define('officeResourceMapping', {
+ officeSlug: DataTypes.TEXT,
+ officeId: DataTypes.TEXT,
+ resourceSlug: DataTypes.TEXT,
+ resourceId: DataTypes.TEXT,
+ }, {});
+ officeResourceMapping.associate = function(models) {
+ // associations can be defined here
+ };
+ return officeResourceMapping;
+};
diff --git a/package-lock.json b/package-lock.json
index 85b4ea6..ec355d4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -120,12 +120,19 @@
"dev": true
},
"axios": {
- "version": "0.18.0",
- "resolved": "https://registry.npmjs.org/axios/-/axios-0.18.0.tgz",
- "integrity": "sha1-MtU+SFHv3AoRmTts0AB4nXDAUQI=",
+ "version": "0.19.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.0.tgz",
+ "integrity": "sha512-1uvKqKQta3KBxIz14F2v06AEHZ/dIoeKfbTRkK1E5oqjDnuEerLmYTgJB5AiQZHJcljpg1TuRzdjDR06qNk0DQ==",
"requires": {
- "follow-redirects": "^1.3.0",
- "is-buffer": "^1.1.5"
+ "follow-redirects": "1.5.10",
+ "is-buffer": "^2.0.2"
+ },
+ "dependencies": {
+ "is-buffer": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.3.tgz",
+ "integrity": "sha512-U15Q7MXTuZlrbymiz95PJpZxu8IlipAp4dtS3wOdgPXx3mqBnslrWU14kxfHB+Py/+2PVKSr37dMAgM2A4uArw=="
+ }
}
},
"babel-runtime": {
@@ -1128,20 +1135,25 @@
}
},
"follow-redirects": {
- "version": "1.7.0",
- "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.7.0.tgz",
- "integrity": "sha512-m/pZQy4Gj287eNy94nivy5wchN3Kp+Q5WgUPNy5lJSZ3sgkVKSYV/ZChMAQVIgx1SqfZ2zBZtPA2YlXIWxxJOQ==",
+ "version": "1.5.10",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz",
+ "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==",
"requires": {
- "debug": "^3.2.6"
+ "debug": "=3.1.0"
},
"dependencies": {
"debug": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
- "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
+ "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
"requires": {
- "ms": "^2.1.1"
+ "ms": "2.0.0"
}
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
}
}
},
@@ -1982,7 +1994,8 @@
"is-buffer": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
- "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="
+ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
+ "dev": true
},
"is-ci": {
"version": "1.2.1",
diff --git a/package.json b/package.json
index b8e611e..cbfe4b6 100644
--- a/package.json
+++ b/package.json
@@ -21,13 +21,14 @@
"node": "11.12.x"
},
"dependencies": {
- "axios": "^0.18.0",
+ "axios": "^0.19.0",
"csv-parser": "^2.3.0",
"dotenv": "^8.0.0",
"express": "^4.17.0",
"express-basic-auth": "^1.2.0",
"formidable": "^1.2.1",
"moment": "^2.24.0",
+ "moment-timezone": "^0.5.25",
"pg": "^7.11.0",
"sequelize": "^5.8.6",
"sequelize-cli": "^5.4.0"
diff --git a/routes/index.js b/routes/index.js
index f5b4e2c..e787596 100644
--- a/routes/index.js
+++ b/routes/index.js
@@ -1,12 +1,15 @@
'use strict';
const { apiStatusCheck } = require('../controllers/apiStatusCheck');
-const { uploadDoorLockData } = require('../controllers/doorLock');
+const { uploadDoorLockData, getKnownOfficeResourceMappings, addNewMapping } = require('../controllers/doorLock');
const express = require('express');
const router = express.Router();
router.get('/', apiStatusCheck);
+
router.post('/doorLock/upload', uploadDoorLockData);
+router.get('/doorLock/mappings', getKnownOfficeResourceMappings);
+router.post('/doorLock/mappings', addNewMapping);
module.exports = router;
diff --git a/server.js b/server.js
index bbb332e..ff8a27d 100644
--- a/server.js
+++ b/server.js
@@ -13,6 +13,8 @@ const app = express();
const port = process.env.PORT || 5000;
+app.use(express.json());
+
app.use('/api', routes);
app.use(basicAuth({
diff --git a/services/doorLock.js b/services/doorLock.js
index 497ae66..38e7a13 100644
--- a/services/doorLock.js
+++ b/services/doorLock.js
@@ -9,14 +9,29 @@ const {
USER_ENTRY_EVENT,
ENABLE_PASSAGE_MODE,
DISABLE_PASSAGE_MODE,
- USER_UNLOCKED_DOOR,
- USER_LOCKED_DOOR,
VALID_CSV_HEADERS,
+ doorLockEvents,
csvParserErrors,
} = require('../constants/constants');
const { fetchAllMembers, findMember } = require('../services/officeRnD/members');
+const { getMappingsFromDatabase } = require('../services/officeRnD/resources');
+const extractMappingFromFileName = (fileName) => {
+ const contentBetweenBracketsRegex = /\[(.*?)\]/;
+ const rawContent = fileName.match(contentBetweenBracketsRegex)[1];
+ const mappingContent = rawContent.split('-').map(word => word.trim());
+ return {
+ officeSlug: mappingContent[0],
+ resourceSlug: mappingContent[1],
+ }
+};
+
+const checkIfMappingExsists = (mappingFromFileName, mappings) => {
+ const { officeSlug, resourceSlug } = mappingFromFileName;
+
+ return mappings.find(mapping => (mapping.officeSlug === officeSlug) && (mapping.resourceSlug === resourceSlug));
+};
const parseDoorLockDataFile = (file) => {
return new Promise ((resolve, reject) => {
@@ -25,8 +40,19 @@ const parseDoorLockDataFile = (file) => {
const unknownMembers = [];
let isValidFile = true;
- fetchAllMembers()
- .then(() => {
+ const prefetchDataJobs = [getMappingsFromDatabase(), fetchAllMembers()];
+
+ Promise.all(prefetchDataJobs)
+ .then(result => {
+ const mappings = result[0];
+
+ const mappingFromFileName = extractMappingFromFileName(file.name);
+ const mappingObject = checkIfMappingExsists(mappingFromFileName, mappings);
+ if (!mappingObject){
+ reject('Error ! File contains unknown location');
+ return;
+ }
+
fs.createReadStream(file.path)
.pipe(csv({
mapHeaders: ({ header, index }) => header.trim().toLowerCase(),
@@ -91,7 +117,9 @@ const parseDoorLockDataFile = (file) => {
}
if (secondEntry && (secondEntry.event === ENABLE_PASSAGE_MODE || secondEntry.event === DISABLE_PASSAGE_MODE)){
- const event = (secondEntry.event === ENABLE_PASSAGE_MODE) ? USER_UNLOCKED_DOOR : USER_LOCKED_DOOR;
+ const event = (secondEntry.event === ENABLE_PASSAGE_MODE) ?
+ doorLockEvents.USER_UNLOCKED : doorLockEvents.USER_LOCKED;
+
const dateTimeString = `${firstEntry.date} ${firstEntry.time}`;
const timestamp = moment.utc(dateTimeString, 'MM/DD/YY HH:mm:ss A').toISOString();
@@ -103,6 +131,8 @@ const parseDoorLockDataFile = (file) => {
memberId: memberObject.memberId,
timestamp,
event,
+ resourceId: mappingObject.resourceId,
+
};
parsedData.push(entryData);
@@ -131,17 +161,19 @@ const parseDoorLockDataFile = (file) => {
errors
});
});
+
})
- .catch((error) => {
+ .catch(error => {
reject(error);
});
});
};
const writeDoorLockEvent = (entry) => {
- db.doorLockEvent.findOrCreate({where: {...entry}, defaults: {...entry}})
- .then()
- .catch();
+ console.log('Write entry : ');
+ console.log(entry);
+ console.log('====');
+ return db.doorLockEvent.findOrCreate({where: {...entry}, defaults: {...entry}});
};
module.exports = {
diff --git a/services/officeRnD/bookings.js b/services/officeRnD/bookings.js
index ad834bd..7fe57e8 100644
--- a/services/officeRnD/bookings.js
+++ b/services/officeRnD/bookings.js
@@ -15,7 +15,7 @@ const fetchAllBookings = () => {
cleanedBookingReservations.push({
reservationId: fullBookingEntry['_id'],
memberId: fullBookingEntry.member,
- resource: fullBookingEntry.resourceId,
+ resourceId: fullBookingEntry.resourceId,
start: fullBookingEntry.start.dateTime,
end: fullBookingEntry.end.dateTime,
});
@@ -29,9 +29,7 @@ const fetchAllBookings = () => {
};
const writeBookingReservation = (bookingReservation) => {
- db.bookingReservation.findOrCreate({where: {...bookingReservation}, defaults: {...bookingReservation}})
- .then()
- .catch();
+ return db.bookingReservation.findOrCreate({where: {...bookingReservation}, defaults: {...bookingReservation}});
};
module.exports = {
diff --git a/services/officeRnD/resources.js b/services/officeRnD/resources.js
new file mode 100644
index 0000000..95b1d64
--- /dev/null
+++ b/services/officeRnD/resources.js
@@ -0,0 +1,61 @@
+'use strict';
+
+const db = require('../../models/index');
+
+const { API } = require('../../helpers/api');
+
+const fetchOffices = () => {
+ return new Promise((resolve, reject) => {
+ API.get('/offices')
+ .then((result) => {
+ const offices = result.data || [];
+ const cleanedOffices = [];
+ offices.forEach(office => {
+ cleanedOffices.push({
+ officeId: office['_id'],
+ officeName: office.name,
+ });
+ });
+ resolve(cleanedOffices);
+ })
+ .catch((error) => {
+ reject(error);
+ });
+ });
+};
+
+const fetchResources = () => {
+ return new Promise((resolve, reject) => {
+ API.get('/resources')
+ .then((result) => {
+ const resources = result.data || [];
+ const cleanedResources = [];
+ resources.forEach(resource => {
+ cleanedResources.push({
+ resourceId: resource['_id'],
+ resourceName: resource.name,
+ officeId: resource.office,
+ });
+ });
+ resolve(cleanedResources);
+ })
+ .catch((error) => {
+ reject(error);
+ });
+ });
+};
+
+const getMappingsFromDatabase = () => {
+ return db.officeResourceMapping.findAll();
+};
+
+const saveNewMappingToDatabase = (mapping) => {
+ return db.officeResourceMapping.findOrCreate({where: {...mapping}, defaults: {...mapping}});
+};
+
+module.exports = {
+ getMappingsFromDatabase,
+ fetchOffices,
+ fetchResources,
+ saveNewMappingToDatabase,
+};