diff --git a/server/handlers/stakeholderHandler.js b/server/handlers/stakeholderHandler.js index d890d9b..3420a63 100644 --- a/server/handlers/stakeholderHandler.js +++ b/server/handlers/stakeholderHandler.js @@ -5,9 +5,10 @@ const { getAllStakeholdersById, getAllStakeholders, createStakeholder, + deleteStakeholder, updateStakeholder, getRelations, - getNonRelations, + // getNonRelations, createRelation, deleteRelation, } = require('../models/Stakeholder'); @@ -22,8 +23,8 @@ const stakeholderGetQuerySchema = Joi.object({ id: Joi.string().uuid(), // organization_id: Joi.number().integer(), // owner_id: Joi.string().uuid(), - limit: Joi.number().integer().greater(0).less(101), - offset: Joi.number().integer().greater(-1), + // limit: Joi.number().integer().greater(0).less(101), + // offset: Joi.number().integer().greater(-1), type: Joi.string(), logo_url: Joi.string(), org_name: Joi.string(), @@ -39,6 +40,18 @@ const stakeholderGetQuerySchema = Joi.object({ filter: Joi.object(), }).unknown(false); +const stakeholderPostSchema = Joi.object({ + type: Joi.string(), + email: Joi.string(), + phone: Joi.string(), +}).unknown(); + +const stakeholderDeleteSchema = Joi.object({ + type: Joi.string(), + email: Joi.string(), + phone: Joi.string(), +}).unknown(); + const stakeholderGetAll = async (req, res, next) => { const filter = req.query.filter ? JSON.parse(req.query.filter) : {}; const query = { ...req.query, filter }; @@ -46,13 +59,11 @@ const stakeholderGetAll = async (req, res, next) => { abortEarly: false, }); const session = new Session(); - const stakeholderRepo = new StakeholderRepository(session); - + const repo = new StakeholderRepository(session); const url = `${req.protocol}://${req.get('host')}/stakeholder`; - - const executeGetAllStakeholders = getAllStakeholders(stakeholderRepo); + const executeGetAll = getAllStakeholders(repo); try { - const result = await executeGetAllStakeholders(query, url); + const result = await executeGetAll(query, url); res.send(result); res.end(); } catch (e) { @@ -68,11 +79,11 @@ const stakeholderGetAllById = async function (req, res, next) { }); const { id } = req.params; const session = new Session(false); - const stakeholderRepo = new StakeholderRepository(session); + const repo = new StakeholderRepository(session); const url = `${req.protocol}://${req.get('host')}/stakeholder`; - const executeGetStakeholders = getAllStakeholdersById(stakeholderRepo, id); + const executeGetById = getAllStakeholdersById(repo, id); try { - const result = await executeGetStakeholders(query, url); + const result = await executeGetById(query, url); res.send(result); res.end(); } catch (e) { @@ -82,36 +93,36 @@ const stakeholderGetAllById = async function (req, res, next) { const stakeholderGetRelations = async function (req, res, next) { const { id } = req.params; - const { isRelation = true, owner_id = null } = req.query; + // const { isRelation = true, org_id = null } = req.query; const session = new Session(false); - const stakeholderRepo = new StakeholderRepository(session); - - if (isRelation !== 'false') { - const executeGetRelations = getRelations(stakeholderRepo, id); - try { - const result = await executeGetRelations(owner_id); - res.send(result); - res.end(); - } catch (e) { - next(e); - } - } else { - const executeGetNonRelations = getNonRelations(stakeholderRepo, id); - try { - const result = await executeGetNonRelations(owner_id); - res.send(result); - res.end(); - } catch (e) { - next(e); - } + const repo = new StakeholderRepository(session); + + // if (isRelation !== 'false') { + const executeGetRelations = getRelations(repo, id); + try { + const result = await executeGetRelations(); + res.send(result); + res.end(); + } catch (e) { + next(e); } + // } else { + // const executeGetNonRelations = getNonRelations(repo, id); + // try { + // const result = await executeGetNonRelations(org_id); + // res.send(result); + // res.end(); + // } catch (e) { + // next(e); + // } + // } }; const stakeholderCreateRelation = async function (req, res, next) { const { id } = req.params; const session = new Session(); - const stakeholderRepo = new StakeholderRepository(session); - const executeCreateRelation = createRelation(stakeholderRepo, id); + const repo = new StakeholderRepository(session); + const executeCreateRelation = createRelation(repo, id); const createStakeholderSchema = Joi.object({ type: Joi.string().required(), @@ -136,8 +147,9 @@ const stakeholderCreateRelation = async function (req, res, next) { const stakeholderDeleteRelation = async function (req, res, next) { const { id } = req.params; const session = new Session(); - const stakeholderRepo = new StakeholderRepository(session); - const executeDeleteRelation = deleteRelation(stakeholderRepo, id); + const repo = new StakeholderRepository(session); + const executeDeleteRelation = deleteRelation(repo, id); + const executeDeleteStakeholder = deleteStakeholder(repo, id); const deleteStakeholderSchema = Joi.object({ type: Joi.string().required(), @@ -151,7 +163,8 @@ const stakeholderDeleteRelation = async function (req, res, next) { abortEarly: false, }); - const result = await executeDeleteRelation(value); + await executeDeleteRelation(value); + const result = await executeDeleteStakeholder(value); res.send(result); res.end(); } catch (e) { @@ -160,46 +173,64 @@ const stakeholderDeleteRelation = async function (req, res, next) { }; const stakeholderCreate = async function (req, res, next) { - const { id } = req.params; + const { id } = req.params || req.body.relation_id; const session = new Session(); - const stakeholderRepo = new StakeholderRepository(session); - - // const eventRepository = new EventRepository(session); - const executeCreateStakeholder = createStakeholder( - stakeholderRepo, - id, - // eventRepository, - ); - - // const eventDispatch = dispatch(eventRepository, publishMessage); + const repo = new StakeholderRepository(session); + const url = `${req.protocol}://${req.get('host')}/stakeholder`; - const stakeholderPostSchema = Joi.object({ - type: Joi.string(), - email: Joi.string(), - phone: Joi.string(), - }).unknown(); + const executeCreate = createStakeholder(repo, id); + const executeCreateRelation = createRelation(repo, id); + const executeGetAll = id + ? getAllStakeholdersById(repo, id) + : getAllStakeholders(repo); try { const value = await stakeholderPostSchema.validateAsync(req.body, { abortEarly: false, }); - // await session.beginTransaction(); - const result = await executeCreateStakeholder({ - ...value, + const data = await executeCreate(value); + await executeCreateRelation({ + type: value.relation, + data: { ...data, relation_id: value.relation_id }, + }); + const result = await executeGetAll({ filter: {} }, url); + + res.status(201).json(result); + } catch (e) { + log.error(e); + next(e); + } +}; + +const stakeholderDelete = async function (req, res, next) { + const { id } = req.params || req.body.relation_id; + const session = new Session(); + const repo = new StakeholderRepository(session); + + const executeDelete = deleteStakeholder(repo, id); + const executeDeleteRelation = deleteRelation(repo, id); + const executeGetAll = id + ? getAllStakeholdersById(repo, id) + : getAllStakeholders(repo); + + try { + const value = await stakeholderDeleteSchema.validateAsync(req.body, { + abortEarly: false, }); + const url = `${req.protocol}://${req.get('host')}/stakeholder`; + delete value.data.parents; + delete value.data.children; + await executeDelete(value.data); + await executeDeleteRelation({ + type: value.type, + data: value.data, + }); + const result = await executeGetAll({ filter: {} }, url); - // await session.commitTransaction(); - // raisedEvents.forEach((domainEvent) => - // eventDispatch('stakeholder-created', domainEvent), - // ); res.status(201).json(result); } catch (e) { log.error(e); - // if (session.isTransactionInProgress()) { - // await session.rollbackTransaction(); - // } - // res.status(422).json({ ...e }); next(e); } }; @@ -207,8 +238,8 @@ const stakeholderCreate = async function (req, res, next) { const stakeholderUpdate = async function (req, res, next) { const { id } = req.params; const session = new Session(); - const stakeholderRepo = new StakeholderRepository(session); - const executeUpdateStakeholder = updateStakeholder(stakeholderRepo, id); + const repo = new StakeholderRepository(session); + const executeUpdateStakeholder = updateStakeholder(repo, id); const updateStakeholderSchema = Joi.object({ id: Joi.string().uuid().required(), @@ -224,9 +255,7 @@ const stakeholderUpdate = async function (req, res, next) { abortEarly: false, }); - const result = await executeUpdateStakeholder({ - ...value, - }); + const result = await executeUpdateStakeholder(value); res.send(result); res.end(); @@ -242,5 +271,6 @@ module.exports = { stakeholderCreateRelation, stakeholderDeleteRelation, stakeholderCreate, + stakeholderDelete, stakeholderUpdate, }; diff --git a/server/models/Stakeholder.js b/server/models/Stakeholder.js index 199cafc..1d3f4a4 100644 --- a/server/models/Stakeholder.js +++ b/server/models/Stakeholder.js @@ -107,6 +107,7 @@ const FilterCriteria = ({ website = null, logo_url = null, map = null, + search = null, }) => { return Object.entries({ id, @@ -122,6 +123,7 @@ const FilterCriteria = ({ website, logo_url, map, + search, }) .filter( (entry) => entry[1] !== undefined && entry[1] !== null && entry[1] !== '', @@ -162,60 +164,103 @@ const makeNextPrevUrls = (url, filter, options) => { return { next, prev }; }; -const getUUID = async (repo, id, options = { limit: 100, offset: 0 }) => { - // check for id in current table first - const stakeholderFound = await repo.getUUIDbyId(id); +const createRelation = (repo, org_id) => async (stakeholder) => { + const id = await getUUID(repo, org_id); - if (!stakeholderFound) { - // get organization from old entity table - const { stakeholders } = await repo.getStakeholderByOrganizationId( - id, - options, - ); + // check both stakeholders exist + // const current = await repo.getById(id); + // const newRelation = await repo.getById(stakeholder.data.id); + + // confirm there's permission to create + // note: owners should have their own id as owner_id + // if ( + // newRelation.owner_id === id || + // current.owner_id === newRelation.owner_id || + // id === null || + // newRelation.owner_id === null + // ) { + const { type, data } = stakeholder; + const insertObj = {}; + + if (type === 'parents' || type === 'children') { + // assign parent and child ids, but if the id is null, look for the relation_id on the data + insertObj.parent_id = type === 'parents' ? data.id : id || data.relation_id; + insertObj.child_id = type === 'children' ? data.id : id || data.relation_id; + } + + const stakeholderRelation = await repo.createRelation(insertObj); + + return stakeholderRelation; + // } + // throw new Error({ + // message: "Whoops! That stakeholder link can't be updated, no permission", + // }); +}; + +async function getUUIDbyId(repo, id, options = { limit: 100, offset: 0 }) { + // get organization from old entity table + const { stakeholders } = await repo.getStakeholderByOrganizationId( + id, + options, + ); - const owner_id = stakeholders[0].stakeholder_uuid; - - stakeholders.forEach(async (entity, i) => { - // console.log('entity to create', entity); - // map from entity fields to stakeholder fields - const stakeholderObj = { - id: entity.stakeholder_uuid, - type: entity.type, - org_name: entity.name, - first_name: entity.first_name, - last_name: entity.last_name, - email: entity.email, - phone: entity.phone, - logo_url: entity.logo_url, - map: entity.map, - website: entity.website, - // pwd_reset_required: entity.pwd_reset_required, - // password: entity.password, - // wallet: entity.wallet, - // salt: entity.salt, - // active_contract_id: entity.active_contract_id, - // offering_pay_to_plant: entity.offering_pay_to_plant, - // tree_validation_contract_id: entity.tree_validation_contract_id, - // organization_id: id, - // owner_id, - }; - - const stakeholder = await repo.createStakeholder(stakeholderObj); - - if (i > 0) { - // if there are relations, create links - await repo.createRelation(owner_id, { - type: 'children', - data: stakeholder, - }); + const org_id = stakeholders[0].stakeholder_uuid; + const exists = await repo.getById(org_id); + + if (!exists) { + const updates = stakeholders.map(async (entity, i) => { + const foundStakeholder = await repo.getById(entity.stakeholder_uuid); + const executeCreateRelation = createRelation(repo, org_id); + + if (!foundStakeholder) { + // console.log('entity to create', entity); + // map from entity fields to stakeholder fields + const stakeholderObj = { + id: entity.stakeholder_uuid, + type: entity.type === 'O' ? 'Organization' : 'Person', + org_name: entity.name, + first_name: entity.first_name, + last_name: entity.last_name, + email: entity.email, + phone: entity.phone, + logo_url: entity.logo_url, + map: entity.map_name, + website: entity.website, + // pwd_reset_required: entity.pwd_reset_required, + // password: entity.password, + // wallet: entity.wallet, + // salt: entity.salt, + // active_contract_id: entity.active_contract_id, + // offering_pay_to_plant: entity.offering_pay_to_plant, + // tree_validation_contract_id: entity.tree_validation_contract_id, + // organization_id: id, + // owner_id, + }; + + const stakeholder = await repo.createStakeholder(stakeholderObj); + + if (i > 0) { + // if there are relations, create links + await executeCreateRelation({ + type: 'children', + data: stakeholder, + }); + } } }); - - return stakeholders[0].stakeholder_uuid; + await Promise.all(updates); } - return stakeholderFound.id; -}; + return org_id; +} + +async function getUUID(repo, org_id) { + const orgId = Number(org_id); + // get organization from old entity table + return org_id === null || Number.isNaN(orgId) + ? org_id + : getUUIDbyId(repo, orgId); +} const getRelationTrees = async (stakeholders, repo) => Promise.all( @@ -248,18 +293,10 @@ const getAllStakeholders = { filter: { where, order, limit, offset }, ...idFilters } = undefined, url, ) => { - let filter = {}; - filter = FilterCriteria({ ...idFilters, ...where }); - - const options = { - ...QueryOptions({ limit, offset, ...order }), - }; - + const filter = FilterCriteria({ ...idFilters, ...where }); + const options = QueryOptions({ limit, offset, ...order }); const { next, prev } = makeNextPrevUrls(url, filter, options); - // get organization from old entity table, enter org id to insert it and it's children - // await getUUID(repo, 1); - let dbStakeholders; let count; @@ -268,6 +305,7 @@ const getAllStakeholders = filter, options, ); + dbStakeholders = stakeholders; count = dbCount; } else { @@ -295,28 +333,16 @@ const getAllStakeholders = }; const getAllStakeholdersById = - (repo, acctStakeholder_id) => + (repo, org_id) => async ({ filter: { where, order }, ...idFilters } = undefined, url) => { - let filter = {}; - filter = FilterCriteria({ ...idFilters, ...where }); - - const options = { - ...QueryOptions({ limit: 100, offset: 0, ...order }), - }; - - // create next and prev urls + const filter = FilterCriteria({ ...idFilters, ...where }); + const options = QueryOptions({ limit: 100, offset: 0, ...order }); const { next, prev } = makeNextPrevUrls( - `${url}/${acctStakeholder_id}`, + `${url}/${org_id}`, filter, options, ); - - const orgId = Number(acctStakeholder_id); - // get organization from old entity table - const id = - acctStakeholder_id === null || Number.isNaN(orgId) - ? acctStakeholder_id - : await getUUID(repo, orgId); + const id = await getUUID(repo, org_id); let dbStakeholders; let count = 0; @@ -352,40 +378,9 @@ const getAllStakeholdersById = }; }; -const getRelations = (repo, current_id) => async (org_id) => { - const orgId = Number(org_id); - // get organization from old entity table - const owner_id = - org_id === null || Number.isNaN(orgId) - ? org_id - : await getUUID(repo, orgId); - - const { stakeholders, count } = await repo.getRelations(current_id, owner_id); - - return { - stakeholders: - stakeholders && - stakeholders.map((row) => { - row.children = []; - row.parents = []; - return StakeholderTree({ ...row }); - }), - totalCount: count, - }; -}; - -const getNonRelations = (repo, current_id) => async (org_id) => { - const orgId = Number(org_id); - // get organization from old entity table - const owner_id = - org_id === null || Number.isNaN(orgId) - ? org_id - : await getUUID(repo, orgId); - - const { stakeholders, count } = await repo.getNonRelations( - current_id, - owner_id, - ); +const getRelations = (repo, current_id) => async () => { + // const id = await getUUID(repo, org_id); + const { stakeholders, count } = await repo.getRelations(current_id); return { stakeholders: @@ -399,136 +394,104 @@ const getNonRelations = (repo, current_id) => async (org_id) => { }; }; -const createRelation = (repo, current_id) => async (stakeholder) => { - const orgId = Number(current_id); - // get organization from old entity table - const id = - current_id === null || Number.isNaN(orgId) - ? current_id - : await getUUID(repo, orgId); - - // check both stakeholders exist - const current = await repo.verifyById(id); - const newRelation = await repo.verifyById(stakeholder.data.id); - - // confirm there's permission to create - // note: owners should have their own id as owner_id - if ( - newRelation.owner_id === id || - current.owner_id === newRelation.owner_id || - id === null || - newRelation.owner_id === null - ) { - const { type, data } = stakeholder; - const insertObj = {}; - - if (type === 'parents' || type === 'children') { - insertObj.parent_id = type === 'parents' ? data.id : id; - insertObj.child_id = type === 'children' ? data.id : id; - } - // need to update db relation table before implementing - // insertObj.grower_id = type === 'growers' ? id : null; - // insertObj.user_id = type === 'users' ? id : null; - - const stakeholderRelation = await repo.createRelation(insertObj); - - return stakeholderRelation; - } - throw new Error({ - message: "Whoops! That stakeholder link can't be updated, no permission", - }); -}; +// const getNonRelations = (repo, current_id) => async (org_id) => { +// const id = await getUUID(repo, org_id); +// const { stakeholders, count } = await repo.getNonRelations(current_id, id); + +// return { +// stakeholders: +// stakeholders && +// stakeholders.map((row) => { +// row.children = []; +// row.parents = []; +// return StakeholderTree({ ...row }); +// }), +// totalCount: count, +// }; +// }; const deleteRelation = (repo, current_id) => async (stakeholder) => { - const orgId = Number(current_id); - // get organization from old entity table - const id = - current_id === null || Number.isNaN(orgId) - ? current_id - : await getUUID(repo, orgId); + const id = await getUUID(repo, current_id); // get relations for owner - const relatedStakeholders = await repo.getRelatedIds(id); + // const relatedStakeholders = await repo.getRelatedIds(id); // check both stakeholders exist - const current = await repo.verifyById(id); - const delRelation = await repo.verifyById(stakeholder.data.id); + // const current = await repo.getById(id); + // const delRelation = await repo.getById(stakeholder.data.id); // confirm there's permission to delete // note: owners should have their own id as owner_id - if ( - relatedStakeholders.includes(delRelation.id) && - (delRelation.owner_id === id || - current.owner_id === delRelation.owner_id || - id === null || - delRelation.owner_id === null || - current.owner_id === null) - ) { - const { type, data } = stakeholder; - const removeObj = {}; - - if (type === 'parents' || type === 'children') { - removeObj.parent_id = type === 'parents' ? data.id : id; - removeObj.child_id = type === 'children' ? data.id : id; - } + // if ( + // relatedStakeholders.includes(delRelation.id) && + // (delRelation.owner_id === id || + // current.owner_id === delRelation.owner_id || + // id === null || + // delRelation.owner_id === null || + // current.owner_id === null) + // ) { + const { type, data } = stakeholder; + const removeObj = {}; + + if (type === 'parents' || type === 'children') { + removeObj.parent_id = type === 'parents' ? data.id : id; + removeObj.child_id = type === 'children' ? data.id : id; + } - const stakeholderRelation = await repo.deleteRelation(removeObj); + const stakeholderRelation = await repo.deleteRelation(removeObj); - return stakeholderRelation; - } - throw new Error( - "Whoops! That stakeholder link can't be updated, no permission", - ); + return stakeholderRelation; + // } + // throw new Error( + // "Whoops! That stakeholder link can't be updated, no permission", + // ); }; const updateStakeholder = - (repo, owner_id = null) => + (repo, org_id = null) => async (data) => { - const orgId = Number(owner_id); - // get organization from old entity table - const id = - owner_id === null || Number.isNaN(orgId) - ? owner_id - : await getUUID(repo, orgId); - + // const id = await getUUID(repo, org_id); const editedStakeholder = StakeholderTree({ ...data }); - const relatedStakeholders = await repo.getRelatedIds(id); - const foundStakeholder = await repo.verifyById(editedStakeholder.id); + // const relatedStakeholders = await repo.getRelatedIds(id); + // const foundStakeholder = await repo.getById(editedStakeholder.id); // confirm they have right to edit - if ( - (id && relatedStakeholders.includes(editedStakeholder.id)) || - foundStakeholder.owner_id === id || - id === null - ) { - // remove children and parents temporarily to update - const { children, parents, ...updateObj } = editedStakeholder; - const stakeholder = await repo.updateStakeholder(updateObj); - - return StakeholderTree({ ...stakeholder, children, parents }); - } - throw new Error({ - message: "Whoops! That stakeholder can't be edited, no permission", - }); + // if ( + // (id && relatedStakeholders.includes(editedStakeholder.id)) || + // foundStakeholder.owner_id === id || + // id === null + // ) { + // remove children and parents temporarily to update + const { children, parents, ...updateObj } = editedStakeholder; + const stakeholder = await repo.updateStakeholder(updateObj); + + return StakeholderTree({ ...stakeholder, children, parents }); + // } + // throw new Error({ + // message: "Whoops! That stakeholder can't be edited, no permission", + // }); }; const createStakeholder = - (repo, owner_id = null) => + (repo, org_id = null) => async (newStakeholder) => { - const orgId = Number(owner_id); - // get organization from old entity table - const id = - owner_id === null || Number.isNaN(orgId) - ? owner_id - : await getUUID(repo, orgId); - + const id = await getUUID(repo, org_id); const stakeholderObj = StakeholderPostObject({ ...newStakeholder, // organization_id: orgId || id, // to prevent it from being 0 - owner_id: id, + // owner_id: id, }); - const stakeholder = await repo.createStakeholder(stakeholderObj); + const stakeholder = await repo.createStakeholder(stakeholderObj, id); + + return StakeholderTree({ ...stakeholder }); + }; + +const deleteStakeholder = + (repo, org_id = null) => + async (removeStakeholder) => { + const id = await getUUID(repo, org_id); + const stakeholder = await repo.deleteStakeholder(removeStakeholder); return StakeholderTree({ ...stakeholder }); }; @@ -537,9 +500,10 @@ module.exports = { getAllStakeholdersById, getAllStakeholders, createStakeholder, + deleteStakeholder, updateStakeholder, getRelations, - getNonRelations, + // getNonRelations, createRelation, deleteRelation, StakeholderTree, diff --git a/server/repositories/StakeholderRepository.js b/server/repositories/StakeholderRepository.js index f62d8d1..60cb587 100644 --- a/server/repositories/StakeholderRepository.js +++ b/server/repositories/StakeholderRepository.js @@ -30,35 +30,31 @@ class StakeholderRepository extends BaseRepository { } async getUUIDbyId(id) { - const stakeholder_id = await this._session + return this._session .getDB()(this._tableName) .select('id') .where('organization_id', id) .first(); - - return stakeholder_id; } - async verifyById(id) { - const stakeholder = await this._session + async getById(id) { + return this._session .getDB()(this._tableName) .select('*') .where('id', id) .first(); - - return stakeholder; } - async getAllStakeholders(options) { + async getAllStakeholders() { // get only non-children to start building trees const results = await this._session .getDB()('stakeholder as s') .select('s.*') .leftJoin('stakeholder_relation as sr', 's.id', 'sr.child_id') .whereNull('sr.child_id') - .orderBy('s.org_name', 'asc') - .limit(Number(options.limit)) - .offset(options.offset); + .orderBy('s.org_name', 'asc'); + // .limit(Number(options.limit)) + // .offset(options.offset); const count = await this._session.getDB()('stakeholder as s').count('*'); @@ -69,25 +65,25 @@ class StakeholderRepository extends BaseRepository { return { stakeholders: results, count: +count[0].count }; } - async getAllStakeholdersById(id = null, options) { + async getAllStakeholdersById(id = null) { // get only non-children to start building trees const results = await this._session .getDB()('stakeholder as s') .select('s.*') .leftJoin('stakeholder_relation as sr', 's.id', 'sr.child_id') .where('s.id', id) - .orWhere('s.owner_id', id) - .andWhere('sr.child_id', null) - .orderBy('s.org_name', 'asc') - .limit(Number(options.limit)) - .offset(options.offset); + // .orWhere('s.owner_id', id) + // .andWhere('sr.child_id', null) + .orderBy('s.org_name', 'asc'); + // .limit(Number(options.limit)) + // .offset(options.offset); // count all the stakeholders, regardless of nesting const count = await this._session .getDB()(this._tableName) .count('*') - .where('id', id) - .orWhere('owner_id', id); + .where('id', id); + // .orWhere('owner_id', id); return { stakeholders: results, count: +count[0].count }; } @@ -162,42 +158,129 @@ class StakeholderRepository extends BaseRepository { return []; } - async getFilter(filter, options) { + async getFilter(filter) { + const searchQuery = ( + query, + search, + // { + // id, + // type, + // org_name, + // first_name, + // last_name, + // email, + // phone, + // website, + // map, + // search, + // }, + ) => { + if (search) { + query.where('org_name', 'ilike', `%${search}%`); + query.orWhere('first_name', 'ilike', `%${search}%`); + query.orWhere('last_name', 'ilike', `%${search}%`); + query.orWhere('email', 'ilike', `%${search}%`); + query.orWhere('phone', 'ilike', `%${search}%`); + query.orWhere('website', 'ilike', `%${search}%`); + query.orWhere('map', 'ilike', `%${search}%`); + } + // if (id) { + // query.where('id', 'ilike', `%${id}%`); + // } + // if (type) { + // query.where('type', 'ilike', `%${type}%`); + // } + // if (org_name) { + // query.where('org_name', 'ilike', `%${org_name}%`); + // } + // if (first_name) { + // query.where('first_name', 'ilike', `%${first_name}%`); + // } + // if (last_name) { + // query.where('last_name', 'ilike', `%${last_name}%`); + // } + // if (email) { + // query.where('email', 'ilike', `%${email}%`); + // } + // if (phone) { + // query.where('phone', 'ilike', `%${phone}%`); + // } + // if (website) { + // query.where('website', 'ilike', `%${website}%`); + // } + // if (map) { + // query.where('map', 'ilike', `%${map}%`); + // } + }; + + const { search = '', org_name = '', ...rest } = filter; + console.log('ORG_NAME', org_name); + const stakeholders = await this._session .getDB()(this._tableName) .select('*') - .where({ ...filter }) - .orderBy('org_name', 'asc') - .limit(Number(options.limit)) - .offset(options.offset); + .where(function () { + this.where({ ...rest }); + this.andWhere('org_name', 'ilike', `%${org_name}%`); + }) + .andWhere(function () { + if (search) { + this.where('org_name', 'ilike', `%${search}%`); + this.orWhere('first_name', 'ilike', `%${search}%`); + this.orWhere('last_name', 'ilike', `%${search}%`); + this.orWhere('email', 'ilike', `%${search}%`); + this.orWhere('phone', 'ilike', `%${search}%`); + this.orWhere('website', 'ilike', `%${search}%`); + this.orWhere('map', 'ilike', `%${search}%`); + } + }) + .orderBy('org_name', 'asc'); + // .limit(Number(options.limit)) + // .offset(options.offset) const count = await this._session .getDB()(this._tableName) .count('*') - .where({ ...filter }); + .where(function () { + this.where({ ...rest }); + this.andWhere('org_name', 'ilike', `%${org_name}%`); + }) + .andWhere(function () { + if (search) { + this.where('org_name', 'ilike', `%${search}%`); + this.orWhere('first_name', 'ilike', `%${search}%`); + this.orWhere('last_name', 'ilike', `%${search}%`); + this.orWhere('email', 'ilike', `%${search}%`); + this.orWhere('phone', 'ilike', `%${search}%`); + this.orWhere('website', 'ilike', `%${search}%`); + this.orWhere('map', 'ilike', `%${search}%`); + } + }); return { stakeholders, count: +count[0].count }; } - async getFilterById(id, filter, options) { + async getFilterById(id, filter) { const relatedIds = await this.getRelatedIds(id); const stakeholders = await this._session .getDB()(this._tableName) .select('*') - .where((builder) => - builder.whereIn('id', relatedIds).orWhere('owner_id', id), + .where( + (builder) => builder.whereIn('id', relatedIds), + // .orWhere('owner_id', id), ) .andWhere({ ...filter }) - .orderBy('org_name', 'asc') - .limit(Number(options.limit)) - .offset(options.offset); + .orderBy('org_name', 'asc'); + // .limit(Number(options.limit)) + // .offset(options.offset); const count = await this._session .getDB()(this._tableName) .count('*') - .where((builder) => - builder.whereIn('id', relatedIds).orWhere('owner_id', id), + .where( + (builder) => builder.whereIn('id', relatedIds), + // .orWhere('owner_id', id), ) .andWhere({ ...filter }); @@ -244,6 +327,22 @@ class StakeholderRepository extends BaseRepository { return created[0]; } + async deleteStakeholder(object) { + const deleted = await this._session + .getDB()(this._tableName) + .where('id', object.id) + .del() + .returning('*'); + + expect(deleted).match([ + { + id: expect.anything(), + }, + ]); + + return deleted[0]; + } + async updateStakeholder(object) { const updated = await this._session .getDB()(this._tableName) @@ -281,16 +380,17 @@ class StakeholderRepository extends BaseRepository { return Array.from(ids); } - async getRelations(id, owner_id) { + async getRelations(id) { const relatedIds = await this.getRelatedIds(id); const ids = relatedIds || []; const stakeholders = await this._session .getDB()(this._tableName) .select('*') - .whereIn('owner_id', [id, owner_id]) - .orWhereNull('owner_id') + // .whereIn('owner_id', [id, owner_id]) + // .orWhereNull('owner_id') .whereIn('id', [...ids, id]) + .orWhereNull('id') .orderBy('org_name', 'asc'); const count = await this._session @@ -301,25 +401,25 @@ class StakeholderRepository extends BaseRepository { return { stakeholders, count: +count[0].count }; } - async getNonRelations(id, owner_id) { - const relatedIds = await this.getRelatedIds(id); - const ids = relatedIds || []; + // async getNonRelations(id, owner_id) { + // const relatedIds = await this.getRelatedIds(id); + // const ids = relatedIds || []; - const stakeholders = await this._session - .getDB()(this._tableName) - .select('*') - .whereIn('owner_id', [id, owner_id]) - .orWhereNull('owner_id') - .whereNotIn('id', [...ids, id]) - .orderBy('org_name', 'asc'); + // const stakeholders = await this._session + // .getDB()(this._tableName) + // .select('*') + // .whereIn('owner_id', [id, owner_id]) + // .orWhereNull('owner_id') + // .whereNotIn('id', [...ids, id]) + // .orderBy('org_name', 'asc'); - const count = await this._session - .getDB()(this._tableName) - .count('*') - .whereNotIn('id', [...ids, id]); + // const count = await this._session + // .getDB()(this._tableName) + // .count('*') + // .whereNotIn('id', [...ids, id]); - return { stakeholders, count: +count[0].count }; - } + // return { stakeholders, count: +count[0].count }; + // } async createRelation(stakeholder) { const linkedStakeholders = await this._session diff --git a/server/routes.js b/server/routes.js index 25f6ecb..6d326a4 100644 --- a/server/routes.js +++ b/server/routes.js @@ -8,6 +8,7 @@ const { stakeholderDeleteRelation, stakeholderUpdate, stakeholderCreate, + stakeholderDelete, } = require('./handlers/stakeholderHandler'); const { handlerWrapper } = require('./utils/utils'); @@ -21,12 +22,14 @@ router .route('/stakeholders/:id') .get(handlerWrapper(stakeholderGetAllById)) .post(handlerWrapper(stakeholderCreate)) - .patch(handlerWrapper(stakeholderUpdate)); + .patch(handlerWrapper(stakeholderUpdate)) + .delete(handlerWrapper(stakeholderDelete)); router .route('/stakeholders') .get(handlerWrapper(stakeholderGetAll)) .post(handlerWrapper(stakeholderCreate)) - .patch(handlerWrapper(stakeholderUpdate)); + .patch(handlerWrapper(stakeholderUpdate)) + .delete(handlerWrapper(stakeholderDelete)); module.exports = router;