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

feat(package-actions): Enable/Disable Formal RAI Response Withdraw #192

Merged
merged 20 commits into from
Nov 15, 2023
Merged
7 changes: 7 additions & 0 deletions src/packages/shared-types/action-types/withdraw-record.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { z } from "zod";

export const withdrawRecordSchema = z.object({
raiWithdrawEnabled: z.boolean(),
});

export type WithdrawRecord = z.infer<typeof withdrawRecordSchema>;
2 changes: 2 additions & 0 deletions src/packages/shared-types/actions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export enum Action {
ENABLE_RAI_WITHDRAW = "enable-rai-withdraw",
DISABLE_RAI_WITHDRAW = "disable-rai-withdraw",
ISSUE_RAI = "issue-rai",
}
1 change: 1 addition & 0 deletions src/packages/shared-types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export * from "./onemac";
export * from "./opensearch";
export * from "./uploads";
export * from "./actions";
export * from "./action-types/withdraw-record";
4 changes: 3 additions & 1 deletion src/packages/shared-types/onemac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ export const onemacSchema = z.object({
submitterName: z.string(),
submitterEmail: z.string(),
attachments: z.array(onemacAttachmentSchema).nullish(),
raiWithdrawEnabled: z.boolean().optional(),
raiResponses: z
.array(
z.object({
additionalInformation: z.string().nullable().default(null),
submissionTimestamp: z.number(),
attachments: z.array(onemacAttachmentSchema),
attachments: z.array(onemacAttachmentSchema).nullish(),
})
)
.nullish(),
Expand Down Expand Up @@ -62,6 +63,7 @@ export const transformOnemac = (id: string) => {
key,
};
}) ?? null,
raiWithdrawEnabled: data.raiWithdrawEnabled,
raiResponses:
data.raiResponses?.map((response) => {
return {
Expand Down
4 changes: 2 additions & 2 deletions src/packages/shared-types/seatool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export const seatoolSchema = z.object({
SPW_STATUS: z
.array(
z.object({
SPW_STATUS_DESC: z.string().nullable(),
SPW_STATUS_DESC: z.string().nullish(),
})
)
.nullable(),
Expand Down Expand Up @@ -144,7 +144,7 @@ export const transformSeatoolData = (id: string) => {
const { leadAnalystName, leadAnalystOfficerId } = getLeadAnalyst(data);
const { raiReceivedDate, raiRequestedDate } = getRaiDate(data);
const { stateStatus, cmsStatus } = getStatus(
data.SPW_STATUS?.[0].SPW_STATUS_DESC
data.SPW_STATUS?.at(-1)?.SPW_STATUS_DESC
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as long as these are always in order i guess

);
return {
id,
Expand Down
75 changes: 75 additions & 0 deletions src/services/api/handlers/action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { response } from "../libs/handler";
import { APIGatewayEvent } from "aws-lambda";
import { getPackage } from "../libs/package/getPackage";
import {
getAuthDetails,
isAuthorized,
lookupUserAttributes,
} from "../libs/auth/user";
import { packageActionsForResult } from "./getPackageActions";
import { Action } from "shared-types";
import { issueRai, toggleRaiResponseWithdraw } from "./packageActions";

export const handler = async (event: APIGatewayEvent) => {
try {
const actionType = event.pathParameters.actionType as Action;
const body = JSON.parse(event.body);
console.log(actionType);
console.log(body);

// Check auth
const result = await getPackage(body.id);
const passedStateAuth = await isAuthorized(event, result._source.state);
if (!passedStateAuth)
return response({
statusCode: 401,
body: { message: "Not authorized to view resources from this state" },
});
if (!result.found)
return response({
statusCode: 404,
body: { message: "No record found for the given id" },
});
const authDetails = getAuthDetails(event);
const userAttr = await lookupUserAttributes(
authDetails.userId,
authDetails.poolId
);

// Check that the package action is available
const actions: Action[] = packageActionsForResult(userAttr, result);
if (!actions.includes(actionType)) {
return response({
statusCode: 401,
body: {
message: `You are not authorized to perform ${actionType} on ${body.id}`,
},
});
}

// Call package action
switch (actionType) {
case Action.ISSUE_RAI:
await issueRai(body.id, Date.now());
break;
case Action.ENABLE_RAI_WITHDRAW:
await toggleRaiResponseWithdraw(body, true);
break;
case Action.DISABLE_RAI_WITHDRAW:
await toggleRaiResponseWithdraw(body, false);
break;
default:
throw `No ${actionType} action available`;
}
return response({
statusCode: 200,
body: { message: "success" },
});
} catch (error) {
console.error({ error });
return response({
statusCode: 500,
body: { message: "Internal server error" },
});
}
};
11 changes: 9 additions & 2 deletions src/services/api/handlers/getPackageActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,20 @@ type GetPackageActionsBody = {

/** Generates an array of allowed actions from a combination of user attributes
* and OS result data */
const packageActionsForResult = (
export const packageActionsForResult = (
user: CognitoUserAttributes,
result: ItemResult
): Action[] => {
const actions = [];
if (isCmsUser(user)) {
actions.push(Action.ENABLE_RAI_WITHDRAW);
if (!result._source.raiWithdrawEnabled) {
// result._source.raiReceivedDate &&
actions.push(Action.ENABLE_RAI_WITHDRAW);
}
if (result._source.raiWithdrawEnabled) {
actions.push(Action.DISABLE_RAI_WITHDRAW);
}
actions.push(Action.ISSUE_RAI);
}
return actions;
};
Expand Down
81 changes: 81 additions & 0 deletions src/services/api/handlers/packageActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import * as sql from "mssql";

const user = process.env.dbUser;
const password = process.env.dbPassword;
const server = process.env.dbIp;
const port = parseInt(process.env.dbPort);
const config = {
user: user,
password: password,
server: server,
port: port,
database: "SEA",
};

import { Action, OneMacSink, transformOnemac } from "shared-types";

Check warning on line 15 in src/services/api/handlers/packageActions.ts

View workflow job for this annotation

GitHub Actions / lint

'OneMacSink' is defined but never used

Check warning on line 15 in src/services/api/handlers/packageActions.ts

View workflow job for this annotation

GitHub Actions / lint

'transformOnemac' is defined but never used
import { produceMessage } from "../libs/kafka";
import { response } from "../libs/handler";

const TOPIC_NAME = process.env.topicName;

export async function issueRai(id: string, timestamp: number) {
console.log("CMS issuing a new RAI");
const pool = await sql.connect(config);
const query = `
Insert into SEA.dbo.RAI (ID_Number, RAI_Requested_Date)
values ('${id}'
,dateadd(s, convert(int, left(${timestamp}, 10)), cast('19700101' as datetime)))
`;
// Prepare the request
const request = pool.request();
request.input("ID_Number", sql.VarChar, id);
request.input("RAI_Requested_Date", sql.DateTime, new Date(timestamp));

const result = await sql.query(query);
console.log(result);
await pool.close();
}

export async function withdrawRai(id, timestamp) {

Check warning on line 39 in src/services/api/handlers/packageActions.ts

View workflow job for this annotation

GitHub Actions / lint

'id' is defined but never used
console.log("CMS withdrawing an RAI");
}

export async function respondToRai(id, timestamp) {
console.log("State respnding to RAI");
}

export async function withdrawPackage(id, timestamp) {
console.log("State withdrawing a package.");
}
Comment on lines +39 to +49
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assuming these are just placeholders

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think Mike put those there


export async function toggleRaiResponseWithdraw(
body: { id: string },
toggle: boolean
) {
const { id } = body;
try {
await produceMessage(
TOPIC_NAME,
id,
JSON.stringify({
raiWithdrawEnabled: toggle,
actionType: toggle
? Action.ENABLE_RAI_WITHDRAW
: Action.DISABLE_RAI_WITHDRAW,
})
);

return response({
statusCode: 200,
body: {
message: "record successfully submitted",
},
});
} catch (err) {
console.log(err);

return response({
statusCode: 500,
});
}
}
4 changes: 2 additions & 2 deletions src/services/api/handlers/submit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const config = {
database: "SEA",
};

import { Kafka, KafkaMessage } from "kafkajs";
import { Kafka, Message } from "kafkajs";
import { OneMacSink, transformOnemac } from "shared-types";

const kafka = new Kafka({
Expand Down Expand Up @@ -117,7 +117,7 @@ async function produceMessage(topic, key, value) {
await producer.connect();
console.log("connected");

const message: KafkaMessage = {
const message: Message = {
key: key,
value: value,
partition: 0,
Expand Down
43 changes: 43 additions & 0 deletions src/services/api/libs/kafka.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Kafka, Message } from "kafkajs";

const kafka = new Kafka({
clientId: "submit",
brokers: process.env.brokerString.split(","),
retry: {
initialRetryTime: 300,
retries: 8,
},
ssl: {
rejectUnauthorized: false,
},
});

export const producer = kafka.producer();

export async function produceMessage(
topic: string,
key: string,
value: string
) {
await producer.connect();

const message: Message = {
key: key,
value: value,
partition: 0,
headers: { source: "micro" },
};
console.log(message);

try {
await producer.send({
topic,
messages: [message],
});
console.log("Message sent successfully");
} catch (error) {
console.error("Error sending message:", error);
} finally {
await producer.disconnect();
}
}
24 changes: 24 additions & 0 deletions src/services/api/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,30 @@ functions:
subnetIds: >-
${self:custom.vpc.privateSubnets}
provisionedConcurrency: ${param:submitProvisionedConcurrency}
action:
handler: handlers/action.handler
maximumRetryAttempts: 0
environment:
region: ${self:provider.region}
osDomain: ${param:osDomain}
dbIp: ${self:custom.dbInfo.ip}
dbPort: ${self:custom.dbInfo.port}
dbUser: ${self:custom.dbInfo.user}
dbPassword: ${self:custom.dbInfo.password}
topicName: ${param:topicName}
brokerString: ${self:custom.brokerString}
events:
- http:
path: /action/{actionType}
method: post
cors: true
authorizer: aws_iam
vpc:
securityGroupIds:
- Ref: SecurityGroup
subnetIds: >-
${self:custom.vpc.privateSubnets}
provisionedConcurrency: ${param:submitProvisionedConcurrency} # reuse submit's concurrency
resources:
Resources:
ApiGateway400ErrorCount:
Expand Down
Loading
Loading