Skip to content

Commit

Permalink
Squashed commit of the following:
Browse files Browse the repository at this point in the history
commit 7563b25
Author: 13bfrancis <[email protected]>
Date:   Thu Nov 9 12:29:20 2023 -0500

    fix build error

commit e3c2c18
Author: 13bfrancis <[email protected]>
Date:   Thu Nov 9 12:12:41 2023 -0500

    fix errors with sink

commit 50e4f86
Author: 13bfrancis <[email protected]>
Date:   Wed Nov 8 15:43:36 2023 -0500

    fix index -1 error

commit d489faa
Author: 13bfrancis <[email protected]>
Date:   Wed Nov 8 15:10:45 2023 -0500

    fix errors and lets reindex

commit 9976017
Author: 13bfrancis <[email protected]>
Date:   Wed Nov 8 11:03:24 2023 -0500

    fix typescript error for tombstone

commit 2f6e865
Author: 13bfrancis <[email protected]>
Date:   Wed Nov 8 09:53:04 2023 -0500

    finished up flow (fingers crossed)

commit 0afb047
Author: 13bfrancis <[email protected]>
Date:   Wed Nov 8 09:09:52 2023 -0500

    fix breadcrumb type error

commit 053441f
Author: 13bfrancis <[email protected]>
Date:   Wed Nov 8 09:06:13 2023 -0500

    remove action-type from schema (not needed)

commit 00eff86
Author: 13bfrancis <[email protected]>
Date:   Wed Nov 8 09:04:18 2023 -0500

    add functionality for sinking actions to opensearch

commit 43eaf99
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 14:47:25 2023 -0500

    bringing in brian

commit d8c4af4
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 14:27:13 2023 -0500

    fix thing

commit b4bbbeb
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 14:19:37 2023 -0500

    brians lib

commit 8b520a5
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 14:15:19 2023 -0500

    yut

commit 1a92952
Merge: c045e36 35b4780
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 13:42:17 2023 -0500

    Merge branch 'master' into issuerai

commit c045e36
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 13:41:20 2023 -0500

    sink

commit f2d7ab6
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 09:38:56 2023 -0500

    basic func

commit e164a3e
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 06:51:17 2023 -0500

    nothing

commit 9970b9c
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 06:48:08 2023 -0500

    form work

commit 9943c17
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 06:02:30 2023 -0500

    base

commit 76081ac
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 05:40:31 2023 -0500

    basic routing setup

commit 5917321
Author: Mike Dial <[email protected]>
Date:   Tue Nov 7 05:35:31 2023 -0500

    Show issue rai for all records for cms user
  • Loading branch information
13bfrancis committed Nov 13, 2023
1 parent 5549f33 commit 0b76490
Show file tree
Hide file tree
Showing 16 changed files with 549 additions and 15 deletions.
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>;
1 change: 1 addition & 0 deletions src/packages/shared-types/actions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +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
);
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.");
}

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

0 comments on commit 0b76490

Please sign in to comment.