Skip to content

Commit

Permalink
feat: auto assign orguid
Browse files Browse the repository at this point in the history
  • Loading branch information
frantzarty committed Jan 8, 2022
1 parent 7500162 commit 6d6cbd2
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 29 deletions.
7 changes: 2 additions & 5 deletions src/controllers/organization.controller.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from 'fs';
import { Organization } from '../models/organizations';

const loadFileIntoString = (path) => {
return new Promise((resolve, reject) => {
Expand All @@ -15,11 +16,7 @@ const loadFileIntoString = (path) => {

export const findAll = async (req, res) => {
return res.json({
'f1c54511-865e-4611-976c-7c3c1f704662': {
name: 'Chia',
icon: await loadFileIntoString('src/assets/organizationIcons/me.svg'),
writeAccess: true,
},
...(await Organization.getHomeOrg()),
'35f92331-c8d7-4e9e-a8d2-cd0a86cbb2cf': {
name: 'chili',
icon: await loadFileIntoString('src/assets/organizationIcons/chili.svg'),
Expand Down
41 changes: 31 additions & 10 deletions src/controllers/project.controller.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import _ from 'lodash';

import { uuid as uuidv4 } from 'uuidv4';
import { sequelize } from '../models/database';
import {
Expand All @@ -9,22 +11,38 @@ import {
Vintage,
CoBenefit,
RelatedProject,
Organization,
} from '../models';

import { optionallyPaginatedResponse, paginationParams } from './helpers';
import ModelTypes from './../models/projects/projects.modeltypes.cjs';

export const create = async (req, res) => {
const newRecord = _.cloneDeep(req.body);
// When creating new projects assign a uuid to is so
// multiple organizations will always have unique ids
const uuid = uuidv4();

newRecord.warehouseProjectId = uuid;

// All new projects are assigned to the home orgUid
const orgUid = _.head(Object.keys(await Organization.getHomeOrg()));
newRecord.orgUid = orgUid;

// The new project is getting created in this registry
newRecord.currentRegistry = orgUid;

// Unless we are overriding, a new project originates in this org
if (!newRecord.registryOfOrigin) {
newRecord.registryOfOrigin = orgUid;
}

try {
await Staging.create({
uuid,
action: 'INSERT',
table: 'Projects',
data: JSON.stringify([req.body]),
data: JSON.stringify([newRecord]),
});
res.json('Added project to stage');
} catch (err) {
Expand All @@ -33,26 +51,27 @@ export const create = async (req, res) => {
};

export const findAll = async (req, res) => {
const { page, limit, search, orgUid, columns, useMock } =
req.query;
const { page, limit, search, orgUid, columns, useMock } = req.query;

if (useMock) {
res.json(ProjectMock.findAll({ ...paginationParams(page, limit) }));
return;
}

const defaultColumns = Object.keys(ModelTypes);

let columnsList = [];
if (columns) {
columnsList = columns.split(',');
// Check to ensure passed in columns are valid
if (columnsList.filter(col => defaultColumns.includes(col)).length !== columnsList.length) {
if (
columnsList.filter((col) => defaultColumns.includes(col)).length !==
columnsList.length
) {
console.error('Invalid column specified');
res.status(400).send('Invalid column specified');
return;
}

} else {
columnsList = defaultColumns;
}
Expand All @@ -62,8 +81,10 @@ export const findAll = async (req, res) => {
let results;

if (search) {
const supportedSearchFields = columnsList.filter(col => !['createdAt', 'updatedAt'].includes(col))

const supportedSearchFields = columnsList.filter(
(col) => !['createdAt', 'updatedAt'].includes(col),
);

if (dialect === 'sqlite') {
results = await Project.findAllSqliteFts(
search,
Expand All @@ -81,7 +102,7 @@ export const findAll = async (req, res) => {
}
return res.json(optionallyPaginatedResponse(results, page, limit));
}

const query = {
attributes: columnsList,
include: [
Expand Down
15 changes: 14 additions & 1 deletion src/controllers/units.controller.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
'use strict';

import _ from 'lodash';

import { uuid as uuidv4 } from 'uuidv4';
import { Staging, UnitMock, Unit, Qualification, Vintage } from '../models';
import { optionallyPaginatedResponse, paginationParams } from './helpers';

export const create = async (req, res) => {
try {
const newRecord = _.cloneDeep(req.body);

// When creating new projects assign a uuid to is so
// multiple organizations will always have unique ids
const uuid = uuidv4();

newRecord.warehouseProjectId = uuid;

// All new units are assigned to the home orgUid
const orgUid = _.head(Object.keys(await Organization.getHomeOrg()));
newRecord.orgUid = orgUid;

// The new unit is getting created in this registry
newRecord.registry = orgUid;

const stagedData = {
uuid,
action: 'INSERT',
table: 'Units',
data: JSON.stringify([req.body]),
data: JSON.stringify([newRecord]),
};

await Staging.create(stagedData);
Expand Down
19 changes: 10 additions & 9 deletions src/models/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Project } from "./projects";
import { CoBenefit } from "./co-benefits";
import { ProjectLocation } from "./locations/index.js";
import { Qualification } from "./qualifications/index.js";
import { Rating } from "./ratings/index.js";
import { RelatedProject } from "./related-projects/index.js";
import { Staging } from "./staging/index.js";
import { Unit } from "./units/index.js";
import { Vintage } from "./vintages/index.js";
import { Project } from './projects';
import { CoBenefit } from './co-benefits';
import { ProjectLocation } from './locations';
import { Qualification } from './qualifications';
import { Rating } from './ratings';
import { RelatedProject } from './related-projects';
import { Staging } from './staging';
import { Unit } from './units';
import { Vintage } from './vintages';

Project.associate();
CoBenefit.associate();
Expand All @@ -27,3 +27,4 @@ export * from './related-projects';
export * from './units';
export * from './vintages';
export * from './staging';
export * from './organizations';
2 changes: 2 additions & 0 deletions src/models/organizations/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './organizations.model.js';
export * from './organizations.mock.js';
8 changes: 8 additions & 0 deletions src/models/organizations/organizations.mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import stub from './organizations.stub.json';

export const CoBenefitsMock = {
findAll: () => stub,
findOne: (id) => {
return stub.find((record) => record.id == id);
},
};
40 changes: 40 additions & 0 deletions src/models/organizations/organizations.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
'use strict';

import fs from 'fs';
import Sequelize from 'sequelize';
const { Model } = Sequelize;
import { sequelize } from '../database';

import ModelTypes from './organizations.modeltypes.cjs';

const loadFileIntoString = (path) => {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, buff) => {
if (err) {
console.error(err);
return;
}
console.log(buff.toString());
resolve(buff.toString());
});
});
};

class Organization extends Model {
static async getHomeOrg() {
return {
'f1c54511-865e-4611-976c-7c3c1f704662': {
name: 'Chia',
icon: await loadFileIntoString('src/assets/organizationIcons/me.svg'),
writeAccess: true,
},
};
}
}

Organization.init(ModelTypes, {
sequelize,
modelName: 'organization',
});

export { Organization };
18 changes: 18 additions & 0 deletions src/models/organizations/organizations.modeltypes.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { uuid: uuidv4 } = require('uuidv4');
const Sequelize = require('sequelize');

module.exports = {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
orgUid: {
type: Sequelize.STRING,
unique: true,
},
name: Sequelize.STRING,
icon: Sequelize.STRING,
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
};
1 change: 1 addition & 0 deletions src/models/organizations/organizations.stub.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
2 changes: 0 additions & 2 deletions src/routes/v1/resources/projects.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ ProjectRouter.get('/', validator.query(querySchema), (req, res) => {
});

const baseSchema = {
orgUid: Joi.string().required(),
currentRegistry: Joi.string().required(),
registryOfOrigin: Joi.string().required(),
originProjectId: Joi.string().required(),
projectId: Joi.string().required(),
Expand Down
2 changes: 0 additions & 2 deletions src/routes/v1/resources/units.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ UnitRouter.get('/', validator.query(querySchema), (req, res) => {
});

const bodySchema = Joi.object({
orgUid: Joi.string().required(),
buyer: Joi.string().required(),
registry: Joi.string().required(),
blockIdentifier: Joi.string().required(),
identifier: Joi.string().required(),
qualifications: Joi.array().min(1).optional(),
Expand Down

0 comments on commit 6d6cbd2

Please sign in to comment.