Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SIMSBIOHUB-621: Handle Bad Deployment Data #1382

Merged
merged 15 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions api/.docker/api/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ ENV PATH ${HOME}/node_modules/.bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/us
# Copy the rest of the files
COPY . ./

# Update log directory file permissions, prevents permission errors for linux environments
RUN chmod -R a+rw data/logs/*

VOLUME ${HOME}

# start api with live reload
Expand Down
5 changes: 3 additions & 2 deletions api/src/openapi/schemas/deployment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,27 @@ import { OpenAPIV3 } from 'openapi-types';
import { GeoJSONFeatureCollection } from './geoJson';

export const getDeploymentSchema: OpenAPIV3.SchemaObject = {
title: 'Deployment',
type: 'object',
// TODO: REMOVE unnecessary columns from BCTW response
additionalProperties: false,
required: [
// BCTW properties
'assignment_id',
'collar_id',
'critter_id',
'device_id',
'attachment_start_date',
'attachment_start_time',
'attachment_end_date',
'attachment_end_time',
'bctw_deployment_id',
'device_id',
'device_make',
'device_model',
'frequency',
'frequency_unit',
// SIMS properties
'deployment_id',
'critter_id',
'critterbase_critter_id',
'critterbase_start_capture_id',
'critterbase_end_capture_id',
Expand Down
42 changes: 42 additions & 0 deletions api/src/openapi/schemas/warning.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { OpenAPIV3 } from 'openapi-types';

export const warningSchema: OpenAPIV3.SchemaObject = {
type: 'object',
description: 'General warning object to inform the user of potential data issues.',
required: ['name', 'message', 'data'],
additionalProperties: false,
properties: {
name: {
type: 'string'
},
message: {
type: 'string'
},
data: {
type: 'object',
properties: {
// Allow any properties
}
},
errors: {
type: 'array',
items: {
anyOf: [
{
type: 'string'
},
{
type: 'object'
}
]
}
}
}
};

export type WarningSchema = {
name: string;
message: string;
data?: Record<string, unknown>;
errors?: (string | Record<string, unknown>)[];
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import chai, { expect } from 'chai';
import { describe } from 'mocha';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import * as db from '../../../../../../database/db';
import { BctwDeploymentService } from '../../../../../../services/bctw-service/bctw-deployment-service';
import { DeploymentService } from '../../../../../../services/deployment-service';
import { getMockDBConnection, getRequestHandlerMocks } from '../../../.././../../__mocks__/db';
import { deleteDeploymentsInSurvey } from './delete';

chai.use(sinonChai);

describe('deleteDeploymentsInSurvey', () => {
afterEach(() => {
sinon.restore();
});

it('should delete all provided deployment records from sims and bctw', async () => {
const dbConnectionObj = getMockDBConnection();
sinon.stub(db, 'getDBConnection').returns(dbConnectionObj);

const { mockReq, mockRes, mockNext } = getRequestHandlerMocks();

mockReq.params = {
projectId: '1',
surveyId: '2'
};
mockReq.body = {
deployment_ids: [3, 4]
};

const mockDeleteSimsDeploymentResponse = { bctw_deployment_id: '123-456-789' };

sinon.stub(DeploymentService.prototype, 'deleteDeployment').resolves(mockDeleteSimsDeploymentResponse);
sinon.stub(BctwDeploymentService.prototype, 'deleteDeployment').resolves();

const requestHandler = deleteDeploymentsInSurvey();

await requestHandler(mockReq, mockRes, mockNext);

expect(mockRes.statusValue).to.equal(200);
});

it('should catch and re-throw an error', async () => {
const dbConnectionObj = getMockDBConnection();
sinon.stub(db, 'getDBConnection').returns(dbConnectionObj);

const { mockReq, mockRes, mockNext } = getRequestHandlerMocks();

mockReq.params = {
projectId: '1',
surveyId: '2'
};
mockReq.body = {
deployment_ids: [3, 4]
};

const mockDeleteSimsDeploymentResponse = { bctw_deployment_id: '123-456-789' };
const mockError = new Error('test error');

sinon.stub(DeploymentService.prototype, 'deleteDeployment').resolves(mockDeleteSimsDeploymentResponse);
sinon.stub(BctwDeploymentService.prototype, 'deleteDeployment').throws(mockError);

const requestHandler = deleteDeploymentsInSurvey();
try {
await requestHandler(mockReq, mockRes, mockNext);
expect.fail();
} catch (actualError) {
expect(actualError).to.eql(mockError);
}
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { RequestHandler } from 'express';
import { Operation } from 'express-openapi';
import { PROJECT_PERMISSION, SYSTEM_ROLE } from '../../../../../../constants/roles';
import { getDBConnection } from '../../../../../../database/db';
import { authorizeRequestHandler } from '../../../../../../request-handlers/security/authorization';
import { BctwDeploymentService } from '../../../../../../services/bctw-service/bctw-deployment-service';
import { ICritterbaseUser } from '../../../../../../services/critterbase-service';
import { DeploymentService } from '../../../../../../services/deployment-service';
import { getLogger } from '../../../../../../utils/logger';

const defaultLog = getLogger('paths/project/{projectId}/survey/{surveyId}/deployments/delete');

export const POST: Operation = [
authorizeRequestHandler((req) => {
return {

Check warning on line 15 in api/src/paths/project/{projectId}/survey/{surveyId}/deployments/delete.ts

View check run for this annotation

Codecov / codecov/patch

api/src/paths/project/{projectId}/survey/{surveyId}/deployments/delete.ts#L15

Added line #L15 was not covered by tests
or: [
{
validProjectPermissions: [PROJECT_PERMISSION.COORDINATOR, PROJECT_PERMISSION.COLLABORATOR],
surveyId: Number(req.params.surveyId),
discriminator: 'ProjectPermission'
},
{
validSystemRoles: [SYSTEM_ROLE.DATA_ADMINISTRATOR],
discriminator: 'SystemRole'
}
]
};
}),
deleteDeploymentsInSurvey()
];

POST.apiDoc = {
description: 'Delete deployments from a survey.',
tags: ['deployment', 'bctw'],
security: [
{
Bearer: []
}
],
parameters: [
{
in: 'path',
name: 'projectId',
schema: {
type: 'integer',
minimum: 1
},
required: true
},
{
in: 'path',
name: 'surveyId',
schema: {
type: 'integer',
minimum: 1
},
required: true
}
],
requestBody: {
description: 'Array of one or more deployment IDs to delete.',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
deployment_ids: {
type: 'array',
items: {
type: 'integer',
minimum: 1
},
minItems: 1
}
}
}
}
}
},
responses: {
200: {
description: 'Delete OK.'
},
400: {
$ref: '#/components/responses/400'
},
401: {
$ref: '#/components/responses/401'
},
403: {
$ref: '#/components/responses/403'
},
409: {
$ref: '#/components/responses/409'
},
500: {
$ref: '#/components/responses/500'
},
default: {
$ref: '#/components/responses/default'
}
}
};

/**
* Delete deployments from a survey.
*
* @export
* @return {*} {RequestHandler}
*/
export function deleteDeploymentsInSurvey(): RequestHandler {
return async (req, res) => {
const surveyId = Number(req.params.surveyId);
const deploymentIds: number[] = req.body.deployment_ids;

const connection = getDBConnection(req.keycloak_token);

try {
await connection.open();

const user: ICritterbaseUser = {
keycloak_guid: connection.systemUserGUID(),
username: connection.systemUserIdentifier()
};

const deletePromises = deploymentIds.map(async (deploymentId) => {
const deploymentService = new DeploymentService(connection);
const { bctw_deployment_id } = await deploymentService.deleteDeployment(surveyId, deploymentId);

const bctwDeploymentService = new BctwDeploymentService(user);
await bctwDeploymentService.deleteDeployment(bctw_deployment_id);
});

await Promise.all(deletePromises);

return res.status(200).send();
} catch (error) {
defaultLog.error({ label: 'deleteDeploymentsInSurvey', message: 'error', error });
await connection.rollback();

throw error;
} finally {
connection.release();
}
};
}
Loading
Loading