Skip to content

Commit

Permalink
feat: assert child label existance when inserting or updating project…
Browse files Browse the repository at this point in the history
…s and units
  • Loading branch information
MichaelTaylor3D committed Feb 8, 2022
1 parent 55c8712 commit ae454a1
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 28 deletions.
58 changes: 41 additions & 17 deletions src/controllers/project.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
Organization,
Rating,
Estimation,
ModelKeys,
} from '../models';

import {
Expand All @@ -28,6 +29,7 @@ import {
assertCsvFileInRequest,
assertHomeOrgExists,
assetNoPendingCommits,
assertRecordExistance,
} from '../utils/data-assertions';

import { createProjectRecordsFromCsv } from '../utils/csv-utils';
Expand Down Expand Up @@ -55,7 +57,7 @@ export const create = async (req, res) => {
const { orgUid } = await Organization.getHomeOrg();
newRecord.orgUid = orgUid;

const childRecords = [
const childRecordsKeys = [
'projectLocations',
'issuances',
'coBenefits',
Expand All @@ -65,23 +67,36 @@ export const create = async (req, res) => {
'labels',
];

childRecords.forEach((childRecordKey) => {
if (newRecord[childRecordKey]) {
newRecord[childRecordKey].map((childRecord) => {
childRecord.id = uuidv4();
const existingChildRecordKeys = childRecordsKeys.filter((key) =>
Boolean(newRecord[key]),
);

for (let i = 0; i < existingChildRecordKeys.length; i++) {
const key = existingChildRecordKeys[i];
await Promise.all(
newRecord[key].map(async (childRecord) => {
if (childRecord.id) {
// If we are reusing an existing child record,
// Make sure it exists
await assertRecordExistance(ModelKeys[key], childRecord.id);
} else {
childRecord.id = uuidv4();
}

childRecord.orgUid = orgUid;
childRecord.warehouseProjectId = uuid;
return childRecord;
});
}
});
}),
);
}

await Staging.create({
uuid,
action: 'INSERT',
table: Project.stagingTableName,
data: JSON.stringify([newRecord]),
});

res.json({ message: 'Project staged successfully' });
} catch (err) {
res.status(400).json({
Expand Down Expand Up @@ -212,7 +227,7 @@ export const update = async (req, res) => {
const newRecord = _.cloneDeep(req.body);
const { orgUid } = await Organization.getHomeOrg();

const childRecords = [
const childRecordsKeys = [
'projectLocations',
'issuances',
'coBenefits',
Expand All @@ -222,10 +237,19 @@ export const update = async (req, res) => {
'labels',
];

childRecords.forEach((childRecordKey) => {
if (newRecord[childRecordKey]) {
newRecord[childRecordKey].map((childRecord) => {
if (!childRecord.id) {
const existingChildRecordKeys = childRecordsKeys.filter((key) =>
Boolean(newRecord[key]),
);

for (let i = 0; i < existingChildRecordKeys.length; i++) {
const key = existingChildRecordKeys[i];
await Promise.all(
newRecord[key].map(async (childRecord) => {
if (childRecord.id) {
// If we are reusing an existing child record,
// Make sure it exists
await assertRecordExistance(ModelKeys[key], childRecord.id);
} else {
childRecord.id = uuidv4();
}

Expand All @@ -237,14 +261,14 @@ export const update = async (req, res) => {
childRecord.warehouseProjectId = newRecord.warehouseProjectId;
}

if (childRecordKey === 'labels' && childRecord.labelUnits) {
if (key === 'labels' && childRecord.labelUnits) {
childRecord.labelUnits.orgUid = orgUid;
}

return childRecord;
});
}
});
}),
);
}

// merge the new record into the old record
let stagedRecord = Array.isArray(newRecord) ? newRecord : [newRecord];
Expand Down
41 changes: 30 additions & 11 deletions src/controllers/units.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
assertCsvFileInRequest,
assertHomeOrgExists,
assetNoPendingCommits,
assertRecordExistance,
} from '../utils/data-assertions';

import { createUnitRecordsFromCsv } from '../utils/csv-utils';
Expand Down Expand Up @@ -48,8 +49,14 @@ export const create = async (req, res) => {
newRecord.orgUid = orgUid;

if (newRecord.labels) {
newRecord.labels.map((childRecord) => {
childRecord.id = uuidv4();
const promises = newRecord.labels.map(async (childRecord) => {
if (childRecord.id) {
// if we are reusing a record, make sure it exists
await assertRecordExistance(Label, childRecord.id);
} else {
childRecord.id = uuidv4();
}

childRecord.orgUid = orgUid;
childRecord.label_unit = {};
childRecord.label_unit.id = uuidv4();
Expand All @@ -59,6 +66,8 @@ export const create = async (req, res) => {

return childRecord;
});

await Promise.all(promises);
}

if (newRecord.issuance) {
Expand All @@ -80,7 +89,7 @@ export const create = async (req, res) => {
});
} catch (error) {
res.status(400).json({
message: 'Batch Upload Failed.',
message: 'Unit Insert Failed to stage.',
error: error.message,
});
}
Expand Down Expand Up @@ -178,12 +187,18 @@ export const findAll = async (req, res) => {
};

export const findOne = async (req, res) => {
console.info('req.query', req.query);
res.json(
await Unit.findByPk(req.query.warehouseUnitId, {
include: Unit.getAssociatedModels(),
}),
);
try {
res.json(
await Unit.findByPk(req.query.warehouseUnitId, {
include: Unit.getAssociatedModels(),
}),
);
} catch (error) {
res.status(400).json({
message: 'Cant find Unit.',
error: error.message,
});
}
};

export const updateFromXLS = async (req, res) => {
Expand Down Expand Up @@ -230,8 +245,10 @@ export const update = async (req, res) => {
updatedRecord.orgUid = orgUid;

if (updatedRecord.labels) {
updatedRecord.labels.map((childRecord) => {
if (!childRecord.id) {
const promises = updatedRecord.labels.map(async (childRecord) => {
if (childRecord.id) {
await assertRecordExistance(Label, childRecord.id);
} else {
childRecord.id = uuidv4();
}

Expand All @@ -250,6 +267,8 @@ export const update = async (req, res) => {

return childRecord;
});

await Promise.all(promises);
}

if (updatedRecord.issuance) {
Expand Down
1 change: 1 addition & 0 deletions src/models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export * from './estimations';
export const ModelKeys = {
unit: Unit,
units: Unit,
label: Label,
labels: Label,
label_unit: LabelUnit,
label_units: LabelUnit,
Expand Down
7 changes: 7 additions & 0 deletions src/utils/data-assertions.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ export const assetNoPendingCommits = async () => {
}
};

export const assertRecordExistance = async (Model, pk) => {
const record = await Model.findByPk(pk);
if (!record) {
throw new Error(`${Model.name} does not have a record for ${pk}`);
}
};

export const assertHomeOrgExists = async () => {
const homeOrg = await Organization.getHomeOrg();
if (!homeOrg) {
Expand Down

0 comments on commit ae454a1

Please sign in to comment.