Skip to content

Commit

Permalink
chore: add Power Automate Webhook notification step to `/upload-submi…
Browse files Browse the repository at this point in the history
…ssion` process (#3047)
  • Loading branch information
jessicamcinchak authored May 1, 2024
1 parent 49730db commit 891e788
Show file tree
Hide file tree
Showing 11 changed files with 1,156 additions and 742 deletions.
34 changes: 32 additions & 2 deletions api.planx.uk/modules/send/s3/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import supertest from "supertest";
import app from "../../../server";
import { expectedPlanningPermissionPayload } from "../../../tests/mocks/digitalPlanningDataMocks";
import { queryMock } from "../../../tests/graphqlQueryMock";

jest.mock("../../saveAndReturn/service/utils", () => ({
markSessionAsSubmitted: jest.fn(),
Expand All @@ -25,6 +26,35 @@ jest.mock("@opensystemslab/planx-core", () => {
});

describe(`uploading an application to S3`, () => {
beforeEach(() => {
queryMock.mockQuery({
name: "GetStagingIntegrations",
data: {
teams: [
{
integrations: {
powerAutomateWebhookURL: "test.azure.com/whatever",
powerAutomateAPIKey: "secret",
},
},
],
},
variables: {
slug: "barnet",
},
});

queryMock.mockQuery({
name: "GetStagingIntegrations",
data: {
teams: [],
},
variables: {
slug: "unsupported-team",
},
});
});

it("requires auth", async () => {
await supertest(app)
.post("/upload-submission/barnet")
Expand All @@ -48,10 +78,10 @@ describe(`uploading an application to S3`, () => {
.post("/upload-submission/unsupported-team")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({ payload: { sessionId: "123" } })
.expect(400)
.expect(500)
.then((res) => {
expect(res.body.error).toMatch(
"Send to S3 is not enabled for this local authority (unsupported-team)",
/No team matching "unsupported-team" found/,
);
});
});
Expand Down
45 changes: 39 additions & 6 deletions api.planx.uk/modules/send/s3/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { NextFunction, Request, Response } from "express";
import { $api } from "../../../client";
import { uploadPrivateFile } from "../../file/service/uploadFile";
import { markSessionAsSubmitted } from "../../saveAndReturn/service/utils";
import axios from "axios";

export async function sendToS3(
req: Request,
Expand All @@ -11,6 +12,8 @@ export async function sendToS3(
// `/upload-submission/:localAuthority` is only called via Hasura's scheduled event webhook, so body is wrapped in a "payload" key
const { payload } = req.body;
const localAuthority = req.params.localAuthority;
const env =
process.env.APP_ENVIRONMENT === "production" ? "production" : "staging";

if (!payload?.sessionId) {
return next({
Expand All @@ -22,9 +25,15 @@ export async function sendToS3(
try {
const { sessionId } = payload;

// Only prototyping with Barnet to begin
// In future, confirm this local authority has an S3 bucket/folder configured in team_integrations or similar
if (localAuthority !== "barnet") {
// Fetch integration credentials for this team
const { powerAutomateWebhookURL, powerAutomateAPIKey } =
await $api.team.getIntegrations({
slug: localAuthority,
encryptionKey: process.env.ENCRYPTION_KEY!,
env,
});

if (!powerAutomateWebhookURL || !powerAutomateAPIKey) {
return next({
status: 400,
message: `Send to S3 is not enabled for this local authority (${localAuthority})`,
Expand All @@ -38,16 +47,40 @@ export async function sendToS3(
const { fileUrl } = await uploadPrivateFile(
exportData,
`${sessionId}.json`,
"barnet-prototype",
);

// Send a notification with the file URL to the Power Automate webook
let webhookResponseStatus: number | undefined;
await axios({
method: "POST",
url: powerAutomateWebhookURL,
adapter: "http",
headers: {
"Content-Type": "application/json",
apiKey: powerAutomateAPIKey,
},
data: {
message: "New submission from PlanX",
environment: env,
file: fileUrl,
},
})
.then((res) => {
// TODO Create & update audit table entry here
webhookResponseStatus = res.status;
})
.catch((error) => {
throw new Error(
`Failed to send submission notification to ${localAuthority}'s Power Automate Webhook (${sessionId}): ${error}`,
);
});

// Mark session as submitted so that reminder and expiry emails are not triggered
markSessionAsSubmitted(sessionId);

// TODO Create and update an audit table entry

return res.status(200).send({
message: `Successfully uploaded submission to S3: ${fileUrl}`,
webhookResponse: webhookResponseStatus,
});
} catch (error) {
return next({
Expand Down
2 changes: 1 addition & 1 deletion api.planx.uk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"private": true,
"dependencies": {
"@airbrake/node": "^2.1.8",
"@opensystemslab/planx-core": "git+https://github.com/theopensystemslab/planx-core#4e67b2e",
"@opensystemslab/planx-core": "git+https://github.com/theopensystemslab/planx-core#28110eb",
"@types/isomorphic-fetch": "^0.0.36",
"adm-zip": "^0.5.10",
"aws-sdk": "^2.1467.0",
Expand Down
Loading

0 comments on commit 891e788

Please sign in to comment.