Skip to content

Commit

Permalink
feat: add unitCount fields to unit and split forms
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelTaylor3D committed May 6, 2022
1 parent 670b6b1 commit fd41e9e
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 68 deletions.
33 changes: 13 additions & 20 deletions src/controllers/units.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@ import {
columnsToInclude,
optionallyPaginatedResponse,
paginationParams,
createSerialNumberStr,
} from '../utils/helpers';

import {
assertOrgIsHomeOrg,
assertUnitRecordExists,
assertSumOfSplitUnitsIsValid,
assertCsvFileInRequest,
assertHomeOrgExists,
assertNoPendingCommits,
Expand Down Expand Up @@ -51,6 +49,7 @@ export const create = async (req, res) => {

newRecord.warehouseUnitId = uuid;
newRecord.timeStaged = Math.floor(Date.now() / 1000);
newRecord.serialNumberBlock = `${newRecord.unitBlockStart}-${newRecord.unitBlockEnd}`;

// All new units are assigned to the home orgUid
const { orgUid } = await Organization.getHomeOrg();
Expand Down Expand Up @@ -270,6 +269,7 @@ export const update = async (req, res) => {
// All new units are assigned to the home orgUid
const { orgUid } = await Organization.getHomeOrg();
updatedRecord.orgUid = orgUid;
updatedRecord.serialNumberBlock = `${updatedRecord.unitBlockStart}-${updatedRecord.unitBlockEnd}`;

if (updatedRecord.labels) {
const promises = updatedRecord.labels.map(async (childRecord) => {
Expand Down Expand Up @@ -382,13 +382,7 @@ export const split = async (req, res) => {

await assertOrgIsHomeOrg(originalRecord.orgUid);

const { unitBlockStart } = assertSumOfSplitUnitsIsValid(
originalRecord.serialNumberBlock,
new RegExp(originalRecord.serialNumberPattern),
req.body.records,
);

let lastAvailableUnitBlock = unitBlockStart;
let totalSplitCount = 0;

const splitRecords = await Promise.all(
req.body.records.map(async (record, index) => {
Expand All @@ -399,18 +393,11 @@ export const split = async (req, res) => {
}

newRecord.unitCount = record.unitCount;
totalSplitCount += record.unitCount;

const newUnitBlockStart = lastAvailableUnitBlock;
lastAvailableUnitBlock += Number(record.unitCount);
const newUnitBlockEnd = lastAvailableUnitBlock;
// move to the next available block
lastAvailableUnitBlock += 1;

newRecord.serialNumberBlock = createSerialNumberStr(
originalRecord.serialNumberBlock,
newUnitBlockStart,
newUnitBlockEnd,
);
newRecord.serialNumberBlock = `${record.unitBlockStart}-${record.unitBlockEnd}`;
newRecord.unitBlockStart = record.unitBlockStart;
newRecord.unitBlockEnd = record.unitBlockEnd;

if (record.unitOwner) {
newRecord.unitOwner = record.unitOwner;
Expand All @@ -430,6 +417,12 @@ export const split = async (req, res) => {
}),
);

if (totalSplitCount !== originalRecord.unitCount) {
throw new Error(
`Your total split coount is ${totalSplitCount} units and the original record is ${originalRecord.unitCount} units`,
);
}

const stagedData = {
uuid: req.body.warehouseUnitId,
action: 'UPDATE',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default {
allowNull: true,
}),
queryInterface.addColumn('units', 'unitCount', {
type: Sequelize.STRING,
type: Sequelize.INTEGER,
allowNull: true,
}),
]);
Expand Down
2 changes: 0 additions & 2 deletions src/models/projects/projects.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -363,8 +363,6 @@ class Project extends Model {
isUpdateComment,
);

console.log('#############', commentChangeList);

return {
projects: [
..._.get(insertChangeList, 'project', []),
Expand Down
45 changes: 15 additions & 30 deletions src/utils/data-assertions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,25 @@
import _ from 'lodash';

import { Organization, Unit, Project, Staging, Meta } from '../models';
import { transformSerialNumberBlock } from '../utils/helpers';
import datalayer from '../datalayer';
import { formatModelAssociationName } from './model-utils.js';
import { getConfig } from '../utils/config-loader';

const { IS_GOVERNANCE_BODY, READ_ONLY, USE_SIMULATOR } = getConfig().APP;
const { IS_GOVERNANCE_BODY, READ_ONLY, USE_SIMULATOR, CHIA_NETWORK } =
getConfig().APP;

export const assertChiaNetworkMatchInConfiguration = async () => {
if (!USE_SIMULATOR) {
const networkInfo = await datalayer.getActiveNetwork();
const network = _.get(networkInfo, 'network_name', '');

if (!network.includes(CHIA_NETWORK)) {
throw new Error(
`Your node is on ${network} but your climate warehouse is set to ${CHIA_NETWORK}, please change your config so they match`,
);
}
}
};

export const assertCanBeGovernanceBody = async () => {
if (IS_GOVERNANCE_BODY !== 'true') {
Expand Down Expand Up @@ -210,31 +223,3 @@ export const assertProjectRecordExists = async (

return record.dataValues;
};

export const assertSumOfSplitUnitsIsValid = (
serialNumberBlock,
serialNumberPattern,
splitRecords,
) => {
const sumOfSplitUnits = splitRecords.reduce(
(previousValue, currentValue) =>
previousValue.unitCount + currentValue.unitCount,
);

const [unitBlockStart, unitBlockEnd, unitCount] = transformSerialNumberBlock(
serialNumberBlock,
serialNumberPattern,
);

if (sumOfSplitUnits !== unitCount) {
throw new Error(
`The sum of the split units is ${sumOfSplitUnits} and the original record is ${unitCount}. These should be the same.`,
);
}

return {
unitBlockStart,
unitBlockEnd,
unitCount,
};
};
4 changes: 2 additions & 2 deletions src/validations/units.validations.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ const unitsBaseSchema = {
.custom(pickListValidation('countries', 'countryJurisdictionOfOwner'))
.required(),
inCountryJurisdictionOfOwner: Joi.string().optional(),
// must be in the form ABC123-XYZ456
serialNumberBlock: Joi.string().required(),
unitBlockStart: Joi.string().required(),
unitBlockEnd: Joi.string().required(),
unitCount: Joi.number().integer().required(),
Expand Down Expand Up @@ -77,6 +75,8 @@ export const unitsSplitSchema = Joi.object({
.items(
Joi.object().keys({
unitCount: Joi.number().required(),
unitBlockStart: Joi.string().required(),
unitBlockEnd: Joi.string().required(),
unitOwner: Joi.string().optional(),
countryJurisdictionOfOwner: Joi.string()
.custom(pickListValidation('countries', 'countryJurisdictionOfOwner'))
Expand Down
17 changes: 8 additions & 9 deletions tests/integration/unit.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,9 @@ describe('Unit Resource Integration Tests', function () {
it('splits an existing unit end-to-end (with simulator)', async function () {
// create and commit the unit to be deleted
const createdUnitResult = await supertest(app).post('/v1/units').send({
serialNumberBlock: 'AXJJFSLGHSHEJ9000-AXJJFSLGHSHEJ9010',
serialNumberPattern: '[.*\\D]+([0-9]+)+[-][.*\\D]+([0-9]+)$',
unitBlockStart: 'AXJJFSLGHSHEJ9000',
unitBlockEnd: 'AXJJFSLGHSHEJ9010',
unitCount: 10,
countryJurisdictionOfOwner: 'Austria',
unitOwner: 'TEST_OWNER',
unitType: 'Reduction - nature',
Expand Down Expand Up @@ -171,10 +172,14 @@ describe('Unit Resource Integration Tests', function () {
records: [
{
unitCount: unitRecord.unitCount - 1,
unitBlockStart: 'AXJJFSLGHSHEJ9000',
unitBlockEnd: 'AXJJFSLGHSHEJ9009',
unitOwner: newUnitOwner,
},
{
unitCount: 1,
unitBlockStart: 'AXJJFSLGHSHEJ9009',
unitBlockEnd: 'AXJJFSLGHSHEJ9010',
},
],
};
Expand Down Expand Up @@ -209,7 +214,7 @@ describe('Unit Resource Integration Tests', function () {
expect(splitRecord1.unitOwner).to.equal(newUnitOwner);
expect(splitRecord2.unitOwner).to.equal(unitRecord.unitOwner);

expect(splitRecord1.unitCount).to.equal(10);
expect(splitRecord1.unitCount).to.equal(9);
expect(splitRecord2.unitCount).to.equal(1);

// Expect the split unitscounts to add up to the original unit count
Expand Down Expand Up @@ -290,9 +295,6 @@ describe('Unit Resource Integration Tests', function () {
'labels', // mapped associated field
'issuance', // mapped associated field
'issuanceId',
'unitBlockStart', // virtual field
'unitBlockEnd', // virtual field
'unitCount', // virtual field
'createdAt', // meta field
'updatedAt', // meta field
]),
Expand Down Expand Up @@ -334,9 +336,6 @@ describe('Unit Resource Integration Tests', function () {
'labels', // mapped associated field
'issuance', // mapped associated field
'issuanceId',
'unitBlockStart', // virtual field
'unitBlockEnd', // virtual field
'unitCount', // virtual field
'createdAt', // meta field
'updatedAt', // meta field
]),
Expand Down
5 changes: 3 additions & 2 deletions tests/test-data/new-unit.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"countryJurisdictionOfOwner": "Netherlands",
"projectLocationId": "lkjw2er1-nj23-1212-532-dsjdx5-k131",
"inCountryJurisdictionOfOwner": "California",
"serialNumberBlock": "AXJJFSLGHSHEJ1000-AXJJFSLGHSHEJ1010",
"serialNumberPattern": "[.*\\D]+([0-9]+)+[-][.*\\D]+([0-9]+)$",
"unitBlockStart": "AXJJFSLGHSHEJ1000",
"unitBlockEnd": "AXJJFSLGHSHEJ1010",
"unitCount": 10,
"vintageYear": 2016,
"unitType": "Removal - nature",
"marketplace": "California Carbon",
Expand Down
5 changes: 3 additions & 2 deletions tests/test-data/update-unit.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"countryJurisdictionOfOwner": "Australia",
"projectLocationId": "UPDATED",
"inCountryJurisdictionOfOwner": "UPDATED",
"serialNumberBlock": "AXJJFSLGHSHEJ2000-AXJJFSLGHSHEJ2010",
"serialNumberPattern": "[.*\\D]+([0-9]+)+[-][.*\\D]+([0-9]+)$",
"unitBlockStart": "AXJJFSLGHSHEJ2000",
"unitBlockEnd": "AXJJFSLGHSHEJ2010",
"unitCount": 10,
"vintageYear": 1970,
"unitType": "Reduction - technical",
"marketplace": "UPDATED",
Expand Down

0 comments on commit fd41e9e

Please sign in to comment.