104 lines
3.0 KiB
JavaScript
104 lines
3.0 KiB
JavaScript
'use strict';
|
|
|
|
const db = require('../../models/index');
|
|
|
|
const { API } = require('../../helpers/api');
|
|
const { officeRnDAPIErrors } = require('../../constants/constants');
|
|
|
|
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,
|
|
rate: resource.rate,
|
|
});
|
|
});
|
|
resolve(cleanedResources);
|
|
})
|
|
.catch((error) => {
|
|
console.log("[Fetch resources] Failed to fetch resources : ", error);
|
|
reject(officeRnDAPIErrors.FAILED_TO_FETCH_RESOURCES);
|
|
});
|
|
});
|
|
};
|
|
|
|
const getResourceMappings = () => {
|
|
return new Promise((resolve, reject) => {
|
|
const fetchJobs = [fetchOffices(), fetchResources()];
|
|
|
|
Promise.all(fetchJobs)
|
|
.then((mappings) => {
|
|
const offices = mappings[0];
|
|
const resources = mappings[1];
|
|
|
|
const officesMap = {};
|
|
const resourcesMap = {};
|
|
|
|
offices.forEach((office) => officesMap[office.officeId] = office);
|
|
resources.forEach((resource) => resourcesMap[resource.resourceId] = resource);
|
|
|
|
resolve({
|
|
officesMap,
|
|
resourcesMap,
|
|
});
|
|
})
|
|
.catch((error) => reject(error));
|
|
});
|
|
};
|
|
|
|
const getMappingsFromDatabase = () => {
|
|
return db.officeResourceMapping.findAll({order: [['id']]});
|
|
};
|
|
|
|
const deleteMappingById = (id) => {
|
|
return db.officeResourceMapping.destroy({where: {id}});
|
|
};
|
|
|
|
const updateMappingById = (id, mapping) => {
|
|
if (mapping.id) {
|
|
delete mapping.id;
|
|
}
|
|
|
|
return db.officeResourceMapping.update(mapping, {where: {id}});
|
|
};
|
|
|
|
const saveNewMappingToDatabase = (mapping) => {
|
|
return db.officeResourceMapping.findOrCreate({where: {...mapping}, defaults: {...mapping}});
|
|
};
|
|
|
|
module.exports = {
|
|
getMappingsFromDatabase,
|
|
fetchOffices,
|
|
fetchResources,
|
|
getResourceMappings,
|
|
saveNewMappingToDatabase,
|
|
deleteMappingById,
|
|
updateMappingById,
|
|
};
|